使用字符串变量作为表达式重命名 Dplyr。

4

我希望能够使用字符串重命名变量,例如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.
1个回答

1
你走在正确的道路上。我们可以使用 !!! 运算符来解析命名列表,使用 rename
> s = list(D = 'A')
> df %>% rename(!!!s)
  D B
1 1 5
2 2 6
3 3 7
4 4 8

1
太棒了!看起来文档在这里 - abalter

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接