How to rename columns with row character values using tidyverse pipeline?

Viewed 224

input:

library(tidyverse)

df <- tibble(
  a = c("z", "x", "y"),
  b = c("m", "n", "o"),
  c = c("p", "q", "r")
)

desired output: replace 2nd and 3rd column names with first row values (2nd and 3rd column).

# A tibble: 3 x 3
  a     m     p    
  <chr> <chr> <chr>
1 z     m     p    
2 x     n     q    
3 y     o     r

This is what I tried so far. As you see I am using the vector c("m", "p") which is not what I want, I want it to be dynamic. I also tried cur_data() but it does not work :/.

df %>% 
  rename_with(
    ~ str_replace(., ., c("m", "p")), tail(names(.), 2)
  )
2 Answers

We can use

library(dplyr)
df %>% 
   rename_with(~  unlist(df[1, -1]),  names(.)[-1])

-output

# A tibble: 3 x 3
#  a     m     p    
#  <chr> <chr> <chr>
#1 z     m     p    
#2 x     n     q    
#3 y     o     r 

Or use rename

df %>% 
       rename(!!! setNames(names(.)[-1], .[1, -1]))

Or could use set_names

df %>% 
     set_names(c(names(.)[1], unlist(.[1, -1])))

It's a bit adventurous, but still can be modified for more columns:

library(dplyr)
library(purrr)


df %>%
  rename_with(~ df %>%
                select(b, c) %>%
                map_chr(., ~ first(.x)), .cols = c(2, 3))


# A tibble: 3 x 3
  a     m     p    
  <chr> <chr> <chr>
1 z     m     p    
2 x     n     q    
3 y     o     r 

Related