1

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?

Brian Smith
  • 1,200
  • 4
  • 16

3 Answers3

1

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


chris jude
  • 467
  • 3
  • 8
1

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
akrun
  • 874,273
  • 37
  • 540
  • 662
0

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
Andre Wildberg
  • 12,344
  • 3
  • 12
  • 29