【发布时间】: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_at或rename_if -
您是否只接受
dplyr解决方案?像names(df) <- str_replace_all(names(df),"oldprefix","newprefix")这样的东西会很好用。