Home > Blockchain >  Find a set of column names and replace them with new names using dplyr
Find a set of column names and replace them with new names using dplyr

Time:12-19

I have below data frame

library(dplyr)
data = data.frame('A' = 1:3, 'CC' = 1:3, 'DD' = 1:3, 'M' = 1:3)

Now let define a vectors of strings which represents a subset of column names of above data frame

Target_Col = c('CC', 'M')

Now I want to find the column names in data that match with Target_Col and then replace them with

paste0('Prefix_', Target_Col)

I prefer to do it using dplyr chain rule.

Is there any direct function available to perform this?

CodePudding user response:

Other solutions can be found here! clickhere

vars<-cbind.data.frame(Target_Col,paste0('Prefix_', Target_Col))

data <- data %>% 
  rename_at(vars$Target_Col, ~ vars$`paste0("Prefix_", Target_Col)`)

or

data %>% rename_with(~ paste0('Prefix_', Target_Col), all_of(Target_Col))


CodePudding user response:

We may use

library(stringr)
library(dplyr)
data %>% 
  rename_with(~ str_c('Prefix_', .x), all_of(Target_Col))
  A Prefix_CC DD Prefix_M
1 1         1  1        1
2 2         2  2        2
3 3         3  3        3

CodePudding user response:

With dplyrs rename_with

library(dplyr)

rename_with(data, function(x) ifelse(x %in% Target_Col, paste0("Prefix_", x), x))
  A Prefix_CC DD Prefix_M
1 1         1  1        1
2 2         2  2        2
3 3         3  3        3
  • Related