R语言 在mutate中传递变量

kupeojn6  于 2023-06-19  发布在  其他
关注(0)|答案(1)|浏览(132)

我有一个包含NA值的数据框 在每一列。我想覆盖这些值。我设置了一个遍历每一列的循环,并应用mutate函数。列名在名称变量中。我在mutate函数中使用它?

df <- data.frame("Colonne1" = c(1, 2, NA, 4, 5, NA), "Colonne2" = c(6, NA, 8, 9, NA, 11), "Colonne3" = c(NA, 13, 14, NA, 16, 17), "Colonne4" = runif(6))
means_ <- colMeans(df, na.rm = TRUE)[-c(ncol(df))]
for(name in names(means_)){
  df <- df %>% mutate(!!name = ifelse(is.na(!!name, Colonne4 * means_[name], !!name)))
}

错误

Error: unexpected '=' in:
"  df <- df %>%
    mutate(!!name ="
ux6nzvsh

ux6nzvsh1#

mutate()中使用across()可能更容易做到这一点-没有理由提前计算平均值:

library(dplyr)
  
set.seed(1234)
df <- data.frame("Colonne1" = c(1, 2, NA, 4, 5, NA), "Colonne2" = c(6, NA, 8, 9, NA, 11), "Colonne3" = c(NA, 13, 14, NA, 16, 17), "Colonne4" = runif(6))
df <- df %>% 
  mutate(across(Colonne1:Colonne3, 
                ~ifelse(is.na(.x), 
                        Colonne4*mean(.x, na.rm=TRUE), 
                        .x)))
df
#>   Colonne1  Colonne2  Colonne3  Colonne4
#> 1 1.000000  6.000000  1.705551 0.1137034
#> 2 2.000000  5.289545 13.000000 0.6222994
#> 3 1.827824  8.000000 14.000000 0.6092747
#> 4 4.000000  9.000000  9.350692 0.6233794
#> 5 5.000000  7.317781 16.000000 0.8609154
#> 6 1.920932 11.000000 17.000000 0.6403106

如果你想知道它在循环中是如何工作的,你可以像下面这样做。首先要注意的是,在mutate()中使用字符串作为变量名时,需要将=更改为:=。您还可以使用!!sym(name)计算名称,这将把它当作mutate()中的变量而不是字符串。

set.seed(1234)
df <- data.frame("Colonne1" = c(1, 2, NA, 4, 5, NA), "Colonne2" = c(6, NA, 8, 9, NA, 11), "Colonne3" = c(NA, 13, 14, NA, 16, 17), "Colonne4" = runif(6))
means_ <- colMeans(df, na.rm = TRUE)[-c(ncol(df))]
for(name in names(means_)){
  df <- df %>% mutate({{name}} := ifelse(is.na(!!sym(name)), Colonne4 * means_[!!name], !!sym(name)))
}
df
#>   Colonne1  Colonne2  Colonne3  Colonne4
#> 1 1.000000  6.000000  1.705551 0.1137034
#> 2 2.000000  5.289545 13.000000 0.6222994
#> 3 1.827824  8.000000 14.000000 0.6092747
#> 4 4.000000  9.000000  9.350692 0.6233794
#> 5 5.000000  7.317781 16.000000 0.8609154
#> 6 1.920932 11.000000 17.000000 0.6403106

创建于2023-06-15带有reprex v2.0.2

相关问题