【问题标题】:Adding prefixes to some variables without touching others?为某些变量添加前缀而不触及其他变量?
【发布时间】:2017-09-25 12:54:41
【问题描述】:

我想从 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))

【问题讨论】:

    标签: r dplyr prefix


    【解决方案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 的帖子所示

    【讨论】:

      【解决方案2】:

      这是另一种可能性:

      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
      

      【讨论】:

      • 对,我一直很草率,我可以用names(df1) %&gt;% inset(!grepl("_",.),paste0("important_",.)[which(!grepl("_",.))]) 修复它,但它不再那么漂亮了,所以我从答案中删除了它
      • (即使没有不需要的which
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-24
      • 1970-01-01
      相关资源
      最近更新 更多