如何使用dplyr为几个变量名添加前缀? [英] How do I add a prefix to several variable names using dplyr?

查看:108
本文介绍了如何使用dplyr为几个变量名添加前缀?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为data.frame中的每个变量名添加一个公共前缀。例如,使用 mtcars 数据,我可以添加前缀cars。使用以下代码:

I'm trying to add a common prefix to each of the variable names in a data.frame. For example, using the mtcars data, I could add the prefix "cars." using the following code:

> data(mtcars)
> names(mtcars)
 [1] "mpg"  "cyl"  "disp" "hp"   "drat" "wt"   "qsec" "vs"  
 [9] "am"   "gear" "carb"
> names(mtcars) <- paste0("cars.", names(mtcars))
> names(mtcars)
 [1] "cars.mpg"  "cars.cyl"  "cars.disp" "cars.hp"  
 [5] "cars.drat" "cars.wt"   "cars.qsec" "cars.vs"  
 [9] "cars.am"   "cars.gear" "cars.carb"

但是,我想这样做是作为管道操作的一部分(即一系列使用%>% ),使用一些 dplyr 语法。看起来像重命名一样()的某些组合应该做的伎俩,但我不知道如何使其工作有没有人有任何想法?

However, I would like to do this as part of a piped operation (i.e., a series of functions strung together using %>%), using some of the dplyr syntax. It seems like some combination of rename and everything() should do the trick, but I don't know how to make it work. Does anyone have any ideas?

推荐答案

的确,你可以使用 rename _ (NSE 重命名本身不起作用):

Indeed, you can use rename_ (NSE rename itself doesn’t work):

data %>% rename_(.dots = setNames(names(.), paste0('cars.', names(.))))

...但老实说,为什么?只需直接分配名称就会更简单,更易读:

… but honestly, why? Just assigning names directly is shorter and more readable:

data %>% setNames(paste0('cars.', names(.)))

这篇关于如何使用dplyr为几个变量名添加前缀?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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