[英]Is it possible to reference a column name with a string?
I've looked up this question before but I can't find a solution to my specific issue.我以前查过这个问题,但我找不到针对我的具体问题的解决方案。
Essentially, it's very easy to transform datasets by writing something like this -本质上,通过编写类似这样的内容来转换数据集非常容易 -
data %>% transform(x1 = ifelse(x1 == 1, x1 + 50, x1))
But I'm having an issue when I try to replace x1 with the string "x1"但是当我尝试用字符串“x1”替换 x1 时遇到问题
data %>% transform("x1" = ifelse("x1" == 1, "x1" + 50, "x1"))
I've tried using "get", such as get("x1"), but errors are thrown.我尝试过使用“get”,例如 get(“x1”),但会引发错误。
Is there any way to do this?有没有办法做到这一点?
With dplyr
, use mutate
使用
dplyr
,使用mutate
library(dplyr)
data %>%
mutate(x1 = ifelse(x1 == 1, x1 + 50, x1))
If we pass a character string, either use mutate_at
如果我们传递一个字符串,要么使用
mutate_at
data %>%
mutate_at(vars('x1'), ~ ifelse( . == 1, . + 50, .))
Or convert to sym
bol and evaluate ( !!
)或转换为
sym
并评估 ( !!
)
data %>%
mutate(!! "x1" := ifelse(!! rlang::sym("x1") == 1,
!! rlang::sym("x1") + 50, !!rlang::sym("x1")))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.