Take the first value in a variable as a variable name in R

Viewed 211

In R, I'm trying to take the first value of a character variable and use it to rename the same variable or even to assign a name to another new variable, but I haven't figured out how to do this.

Example:

PR <- data.frame("Variable1" = c("Red", "Blue", "Green", "Yellow"), 
"Variable2" = seq(1:4))

PR
      Variable1 Variable2
1       Red         1
2      Blue         2
3     Green         3
4    Yellow         4

I know one could just use "PR %>% rename(Red = Variable1)", but I want R to take this name from the variable directly. The outcome should be:

       Red      Variable2
1       Red         1
2      Blue         2
3     Green         3
4    Yellow         4

I've trayed to use "rename()" function from dplyr to make it but it didn't work:

 PR <- PR %>% rename(as.name(Variable1)[1] = Variable1)
Error: unexpected '=' in "PR <- PR %>% rename(as.name(Variable1)[1] ="

How could I do this using dplyr, or even in the context of creating a new variable with the "mutate()" command (for example if I want to create a new variable which name is the first value of "Variable1")?

3 Answers

Does this work:

> PR
  Variable1 Variable2
1       Red         1
2      Blue         2
3     Green         3
4    Yellow         4
> name <- PR$Variable1[1]
> PR %>% rename(!!sym(name) := Variable1)
     Red Variable2
1    Red         1
2   Blue         2
3  Green         3
4 Yellow         4
> 

You need to use a special substitute.

library(tidyverse)

PR <- data.frame("Variable1" = c("Red", "Blue", "Green", "Yellow"), 
                 "Variable2" = seq(1:4))

#Note the sequence of commands
PR %>%
  mutate(Variable3 = PR$Variable1[1]) %>%
  rename(!!PR$Variable1[1] := Variable1)

#      Red Variable2 Variable3
# 1    Red         1       Red
# 2   Blue         2       Red
# 3  Green         3       Red
# 4 Yellow         4       Red

We can use rename_at

library(dplyr)
PR %>% 
    rename_at(vars(Variable1), ~ PR$Variable1[1])
#.     Red Variable2
#1    Red         1
#2   Blue         2
#3  Green         3
#4 Yellow         4
Related