我希望能够使用字符串重命名变量,例如df %>% rename(string_var)
,并使用string_var = "A=B"
之类的内容。
有许多类似的问题,但没有完全符合或参考已过时的dplyr
。
从如下数据框开始:
df = data.frame(
A=1:4,
B=5:8
)
我可以使用字符串变量作为条件来过滤:
s = "A<4 & B>5"
by
> df %>% filter(!!rlang::parse_expr(s))
A B
1 2 6
2 3 7
或者
> df %>% filter(eval(str2expression(s)))
A B
1 2 6
2 3 7
我不知道如何使用rename
完成相同的操作。
> s = "D=A"
> df %>% rename(!!rlang::parse_expr(s))
Error: object 'A' not found
> df %>% rename(eval(str2expression(s)))
Error: object 'A' not found
我也尝试过
> l = list(D="A")
> l
$D
[1] "A"
> df %>% rename(l)
Note: Using an external vector in selections is ambiguous.
i Use `all_of(l)` instead of `l` to silence this message.
i See <https://tidyselect.r-lib.org/reference/faq-external-vector.html>.
This message is displayed once per session.
Error: Must rename columns with a valid subscript vector.
x Subscript has the wrong type `list`.
i It must be numeric or character.
Run `rlang::last_error()` to see where the error occurred.
> df %>% rename(!!l)
Error: Must rename columns with a valid subscript vector.
x Subscript has the wrong type `list`.
i It must be numeric or character.
Run `rlang::last_error()` to see where the error occurred.