Afiq Johari
Afiq Johari

Reputation: 1462

dplyr Rename column using another column name as reference

df <- tibble(material = c(1:10)
       ,x2 = c(letters[1:10]))

# A tibble: 10 x 2
   material x2   
      <int> <chr>
 1        1 a    
 2        2 b    
 3        3 c    
 4        4 d    
 5        5 e    
 6        6 f    
 7        7 g    
 8        8 h    
 9        9 i    
10       10 j


colnames(df)[2] <- paste0('text_',colnames(df)[1])                     
colnames(df)[1] <- paste0('key_',colnames(df)[1])

# A tibble: 10 x 2
   key_material text_material
          <int> <chr>        
 1            1 a            
 2            2 b            
 3            3 c            
 4            4 d            
 5            5 e            
 6            6 f            
 7            7 g            
 8            8 h            
 9            9 i            
10           10 j 

I'm trying to rename the second column (x2) based on the initial first column name (material) First column will be renamed 'key_material' and second column will be renamed 'text_material'.

I want to turn the above steps into %>% flow.

Below my attempt

df %>% rename( paste0('text_', colnames(.)[1]) = 2
                     ,paste0('key_', colnames(.)[1]) = 1)

Although it seems that it wouldn't evaluate the expression.

Thanks!

Upvotes: 0

Views: 480

Answers (2)

Roman
Roman

Reputation: 17648

you can try

df  %>% set_names(paste0(c("key_","text_"), names(.)[1]))

when more than two columns you can do

df %>% set_names(c(paste0(c("key_","text_"), names(.)[1]), names(.)[-1:-2]))

Upvotes: 2

Ronak Shah
Ronak Shah

Reputation: 388817

You can use rename_all if you have only 2 columns.

library(dplyr)
df %>% rename_all(~paste(c('key', 'text'), .[1], sep = "_"))

# A tibble: 10 x 2
#   key_material text_material
#          <int> <chr>        
# 1            1 a            
# 2            2 b            
# 3            3 c            
# 4            4 d            
# 5            5 e            
# 6            6 f            
# 7            7 g            
# 8            8 h            
# 9            9 i            
#10           10 j          

Or rename_at if you have more columns but want to rename only first 2.

df %>% rename_at(1:2, ~paste(c('key', 'text'), .[1], sep = "_"))

Upvotes: 3

Related Questions