简体   繁体   中英

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

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

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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM