为某些变量添加前缀而不触及其他变量?

时间:2017-09-25 12:54:42

标签: r dplyr prefix

我希望从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))

2 个答案:

答案 0 :(得分: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的帖子

所示

答案 1 :(得分:0)

这是另一种可能性:

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