简体   繁体   English

dplyr :: mutate_at用于更改前缀?

[英]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. 我有一个带有三个变量的数据帧(df),其中两个带有前缀abc,一个带有前缀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. 我想使用dplyr()更改以abc开头的变量的前缀,以使它们的前缀改为new。

The problems that my current code's not working and I don't understand why. 我当前的代码无法正常工作并且我不理解为什么的问题。

Thanks! 谢谢!

Starting point (df): 起点(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): 期望的结果(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 如果我们需要使用dplyr

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

Or with base R 或与base R

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM