在R,我要重命名所有以一些前缀开始的列(说"oldprefix1", "oldprefix2", "oldprefix3", ...来"newprefix1", "newprefix2", "newprefix3", ...)函数内部.以下代码有效:
change = function(df) {
select(df, newprefix = starts_with('oldprefix') )
}
change(test)
Run Code Online (Sandbox Code Playgroud)
但是,我想将带有新前缀的字符串作为参数传递给函数:
change2 = function(df, prefix) {
dots = paste0(prefix," = starts_with('oldprefix')"
select_(df, dots)
}
change2(test, "newprefix")
Run Code Online (Sandbox Code Playgroud)
我尝试过使用select_()和.dots,但我不能让它与该starts_with()功能一起使用.我收到了错误Error in eval(expr, envir, enclos) :
could not find function "starts_with".
选项是使用 rename_at
mtcars %>%
rename_at(vars(starts_with('m')), funs(paste0('prefix', .)))
Run Code Online (Sandbox Code Playgroud)
要更改旧名称,请使用 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"
Run Code Online (Sandbox Code Playgroud)