R 在不接触其他变量的情况下为某些变量添加前缀?

R 在不接触其他变量的情况下为某些变量添加前缀?,r,dplyr,prefix,R,Dplyr,Prefix,我想从df1生成一个类似df3的数据帧,即在没有前缀的变量中添加一个前缀important_uu,同时不接触带有特定前缀gea_uu、win_u、hea_u的变量。到目前为止,我只管理过类似于df2的东西,其中重要的变量在一个单独的数据帧中结束,但我希望所有变量都在同一个数据帧中。如果您对此有任何想法,我们将不胜感激 我得到的是: library(dplyr) df1 <- data.frame("hea_income"=c(45000,23465,89522),"gea_propert

我想从df1生成一个类似df3的数据帧,即在没有前缀的变量中添加一个前缀important_uu,同时不接触带有特定前缀gea_uu、win_u、hea_u的变量。到目前为止,我只管理过类似于df2的东西,其中重要的变量在一个单独的数据帧中结束,但我希望所有变量都在同一个数据帧中。如果您对此有任何想法,我们将不胜感激

我得到的是:

library(dplyr)

df1 <- data.frame("hea_income"=c(45000,23465,89522),"gea_property"=c(1,1,2) ,"win_state"=c("AB","CA","GA"), "education"=c(1,2,3), "commute"=c(13,32,1))

df2 <- df1 %>% select(-contains("gea_")) %>% select(-contains("win_")) %>% select(-contains("hea_"))  %>% setNames(paste0('important_', names(.)))
我想要的是:

df3 <- data.frame("hea_income"=c(45000,23465,89522),"gea_property"=c(1,1,2) ,"win_state"=c("AB","CA","GA"), "important_education"=c(1,2,3), "important_commute"=c(13,32,1))
一个选项是在

或者用火柴和-


上述三种解决方案都能达到预期效果,如OP的帖子所示

names(df1) <- names(df1) %>% {ifelse(grepl("_",.),.,paste0("important_",.))}
# > df1
#   hea_income gea_property win_state important_education important_commute
# 1      45000            1        AB                   1                13
# 2      23465            1        CA                   2                32
# 3      89522            2        GA                   3                 1

是的,我一直很邋遢,我可以用namedf1%>%inset修复它!grepl_uu,,,paste0important_u,[哪个!grepl_u,.]但是它真的不再那么漂亮了,所以我从答案中删除了它,即使没有不必要的相关内容:
df1 %>%
    rename_at(vars(matches("^[^_]*$")), funs(paste0("important_", .)))
#   hea_income gea_property win_state important_education important_commute
#1      45000            1        AB                   1                13
#2      23465            1        CA                   2                32
#3      89522            2        GA                   3                 1
df1 %>%
    rename_at(vars(-matches("_")), funs(paste0("important_", .)))
#   hea_income gea_property win_state important_education important_commute
#1      45000            1        AB                   1                13
#2      23465            1        CA                   2                32
#3      89522            2        GA                   3                 1
names(df1) <- names(df1) %>% {ifelse(grepl("_",.),.,paste0("important_",.))}
# > df1
#   hea_income gea_property win_state important_education important_commute
# 1      45000            1        AB                   1                13
# 2      23465            1        CA                   2                32
# 3      89522            2        GA                   3                 1