abalter
abalter

Reputation: 10383

Dplyr rename using string variable as expression

I want to be able to rename variables using a string such as df %>% rename(string_var) with something like string_var = "A=B".

Many similar questions, none quite apply or refer to deprecated dplyr.

Starting with a dataframe like

df = data.frame(
  A=1:4,
  B=5:8
)

I can filter using a string variable as the condition:

s = "A<4 & B>5"

by

> df %>% filter(!!rlang::parse_expr(s))
  A B
1 2 6
2 3 7

or

> df %>% filter(eval(str2expression(s)))
  A B
1 2 6
2 3 7

I can't figure out how to do the same with 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

I also tried

> 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.

Upvotes: 5

Views: 653

Answers (1)

Colin H
Colin H

Reputation: 660

You're very much on the right path. We can use the !!! operator to parse named lists using rename.

> s = list(D = 'A')
> df %>% rename(!!!s)
  D B
1 1 5
2 2 6
3 3 7
4 4 8

Upvotes: 2

Related Questions