使用 `starts_with()` 重命名列,其中新前缀是一个字符串 [英] Rename columns using `starts_with()` where new prefix is a string

查看:27
本文介绍了使用 `starts_with()` 重命名列,其中新前缀是一个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In R, I want to rename all the columns that starts with some prefix (say "oldprefix1", "oldprefix2", "oldprefix3", ... to "newprefix1", "newprefix2", "newprefix3", ...) inside a function. The following code works:

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

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

But, I would like to pass a string with the new prefix as parameter to the function:

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) :找不到函数starts_with".

I have tried using select_() and .dots, but I cannot get it to work together with the starts_with() function. I get the error Error in eval(expr, envir, enclos) : could not find function "starts_with".

推荐答案

可以选择使用 rename_at

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

要更改旧名称,请使用 sub

For changing an old name, use 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"    

这篇关于使用 `starts_with()` 重命名列,其中新前缀是一个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆