R:如何使用 'for' 循环使用 dplyr 的 mutate 创建变量?

0 loops r dplyr

我想使用 dplyr 的“mutate”在循环中创建变量。我有4个变量a)yield_corn_total,b)yield_soybeans_total,c)yield_wheat_total,d)yield_sorghum_total。我想创建 4 个其他变量,它们是这 4 个现有变量的日志,它们应该命名为 a) log_yield_corn_total, b) log_yield_soybeans_total, c) log_yield_wheat_total, d) log_yield_sorghum_total

当我运行以下代码时:

 crops <- c( "corn", "soybeans", "wheat", "sorghum")
    data <- data %>% 
      for (i in crops){ 
      mutate(sym(paste0("log_yield_",i,"_total")) := log(paste0("yield_",i,"_total")))
    }
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

Error in for (. in i) crops : 
  4 arguments passed to 'for' which requires 3
Run Code Online (Sandbox Code Playgroud)

Gre*_*gor 6

不要使用for循环,使用across(). 这是未经测试的,因为您没有提供示例数据,但它应该可以工作 - 如果没有,请提供一些示例数据以进行调试,例如dput(data[1:4, ])

crops <- c( "corn", "soybeans", "wheat", "sorghum")
cols = paste("yield", crops, "total", sep = "_")
data %>%
  mutate(across(all_of(cols), log, .names = "log_{.col}"))
Run Code Online (Sandbox Code Playgroud)

  • @langtang只要数据中没有名为“`cols`”的列即可。在大多数情况下可能没问题,但我想说这里使用“all_of()”通常是更好的做法。 (2认同)