2017-10-05 12 views
1

在R中,我希望重命名在函数内部以某个前缀开头的所有列(如"oldprefix1", "oldprefix2", "oldprefix3", ..."newprefix1", "newprefix2", "newprefix3", ...)。下面的代码工作:使用`starts_with()`重新命名字段,其中新的前缀是一个字符串

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"

+0

如果要重命名,然后使用'rename_at'或'rename_if' – akrun

+0

你只对'dplyr'解决方案开放?像'names(df)< - str_replace_all(名称(df),“oldprefix”,“newprefix”)就好用了。 –

回答

2

选项是使用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"  
相关问题