代码之家  ›  专栏  ›  技术社区  ›  LLL

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

  •  1
  • LLL  · 技术社区  · 7 年前

    我想从df1生成一个类似df3的数据帧,即在没有前缀的变量中添加前缀(important_),同时不接触具有特定前缀(gea_、win_、hea_)的变量。到目前为止,我只管理了像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))
    
    2 回复  |  直到 7 年前
        1
  •  1
  •   akrun    7 年前

    一种选择是 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
  •  0
  •   moodymudskipper    7 年前

    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