LLL
LLL

Reputation: 743

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

Upvotes: 1

Views: 430

Answers (1)

akrun
akrun

Reputation: 886948

If we need to use dplyr

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

Or with base R

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

Upvotes: 2

Related Questions