5

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.

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

Sweet! Looks like the docs are here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.