简体   繁体   中英

dplyr::mutate_at for changing prefixes?

I've got a data frame (df) with three variables, two of which have the prefix abc and one with the prefix def.

I'd like to use dplyr() to change the prefix of the variables starting with abc, so that they instead have the prefix new.

The problems that my current code's not working and I don't understand why.

Thanks!

Starting point (df):

df <- data.frame(abc_question1_F1_Q1=c(1,2,1,2),abc_question_F1_Q2=c(1,2,1,2),def_question1_F1_Q3=c(1,2,1,2))

Desired outcome (dfgoal):

df <- data.frame(new_question1_F1_Q1=c(1,2,1,2),new_question_F1_Q2=c(1,2,1,2),def_question1_F1_Q3=c(1,2,1,2))

Current code:

library(dplyr)
df <- df %>% mutate_at(vars(contains("abc_")), function(x){gsub("abc_", "new_", x)})

If we need to use dplyr

df %>% 
   rename_all(funs(sub("^abc", "new", .)))

Or with base R

names(df) <- sub("^abc", "new", names(df))

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