繁体   English   中英

dplyr行式突变,不使用硬编码名称

[英]dplyr rowwise mutate without hardcoding names

我想做这样的事情

df <- iris %>%
  rowwise %>%
  mutate(new_var = sum(Sepal.Length, Sepal.Width))

除了我不想输入变量名,例如

names_to_add <- c("Sepal.Length", "Sepal.Width")
df <- iris %>%
  rowwise %>%
[some function that uses names_to_add]

我尝试了一些事情,例如

df <- iris %>%
  rowwise %>%
  mutate(new_var = sum(sapply(names_to_add, get, envir = as.environment(.))))

但仍然无法弄清楚。 我将回答一个与lazyeval或更简单的答案有关的答案。 请注意,这里的sum函数只是一个占位符,而我的实际函数要复杂得多,尽管它每行返回一个值。 我也宁愿不使用data.table

您应该在dplyrdplyr_结尾的所有功能。 例如mutate_summarise_

names_to_add <- ("sum(Sepal.Length, Sepal.Width)")   

df <- iris %>%
  rowwise %>% mutate_(names_to_add)

编辑

代码的结果:

df <- iris %>%
 rowwise %>% mutate(new_var = sum(Sepal.Length, Sepal.Width))

names_to_add <- ("sum(Sepal.Length, Sepal.Width)")   

df2 <- iris %>%
    rowwise %>% mutate_(new_var = names_to_add)

identical(df, df2)
[1] TRUE

编辑

我编辑了答案,它解决了问题。 我不知道为什么要这样做。

我们使用SE(标准评估),在'mutate_'内部传递字符串作为输入。 更多信息: vignette("nse","dplyr")

x <- "Sepal.Length + Sepal.Width"
df <- mutate_(iris, x)
head(df)

输出:

   Sepal.Length Sepal.Width Petal.Length Petal.Width Species Sepal.Length + Sepal.Width
1          5.1         3.5          1.4         0.2  setosa                        8.6
2          4.9         3.0          1.4         0.2  setosa                        7.9
3          4.7         3.2          1.3         0.2  setosa                        7.9
4          4.6         3.1          1.5         0.2  setosa                        7.7
5          5.0         3.6          1.4         0.2  setosa                        8.6
6          5.4         3.9          1.7         0.4  setosa                        9.3

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM