在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
函数。 - akrundplyr
的解决方案?类似names(df) <- str_replace_all(names(df),"oldprefix","newprefix")
这样的方法会很好地解决问题。 - Michael Bird