【问题标题】:Rename columns using `starts_with()` where new prefix is a string使用 `starts_with()` 重命名列,其中新前缀是字符串
【发布时间】:2018-03-17 01:16:57
【问题描述】:

在 R 中,我想重命名函数中所有以某个前缀开头的列(比如 "oldprefix1", "oldprefix2", "oldprefix3", ..."newprefix1", "newprefix2", "newprefix3", ...)。以下代码有效:

change = function(df) {
    select(df, newprefix = starts_with('oldprefix') )
}
change(test)

但是,我想将带有新前缀的字符串作为参数传递给函数:

change2 = function(df, prefix) {
    dots = paste0(prefix," = starts_with('oldprefix')"
    select_(df, dots)
}
change2(test, "newprefix")

我尝试过使用select_().dots,但我无法让它与starts_with() 函数一起使用。我收到错误Error in eval(expr, envir, enclos) : could not find function "starts_with"

【问题讨论】:

  • 如果要重命名,请使用rename_atrename_if
  • 您是否只接受dplyr 解决方案?像names(df) <- str_replace_all(names(df),"oldprefix","newprefix") 这样的东西会很好用。

标签: r dplyr rename


【解决方案1】:

选项是使用rename_at

mtcars %>% 
    rename_at(vars(starts_with('m')), funs(paste0('prefix', .)))

要更改旧名称,请使用sub

change2 <- function(df, oldpref, newpref) {
  df %>%
       rename_at(vars(starts_with(oldpref)), funs(sub(oldpref, newpref, .)))


 }

change2(mtcars, "m", "newprefix") %>%
       names
#[1] "newprefixpg" "cyl"         "disp"        "hp"          "drat" 
#[6]   "wt"          "qsec"        "vs"          "am"          "gear" 
#[11] "carb"    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-05
    • 2010-09-17
    • 2012-11-10
    • 1970-01-01
    • 2017-01-09
    • 2019-11-03
    • 2021-08-02
    相关资源
    最近更新 更多