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

Adding prefixes to some variables without touching others?

我想从 df1 生成类似 df3 的数据框,即向没有前缀的变量添加前缀 (important_),同时不触及具有某些前缀 (gea_、win_、hea_) 的变量。到目前为止,我只管理过 df2 之类的东西,其中 important_ 变量最终出现在一个单独的数据框中,但我希望所有变量都在同一个数据框中。对此有任何想法将不胜感激。

我得到的:

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

一个选项是rename_at

dfN <- df1 %>%
         rename_at(4:5, funs(paste0("important_", .)))
identical(dfN, df3)
#[1] TRUE

如果我们想指定变量而不是数字索引,我们也可以包含一些正则表达式。这里假设所有那些还没有 _

的列
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

matches-

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

上述所有三种解决方案都获得了 OP post

中所示的预期输出

还有一种可能:

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