简体   繁体   English

怎么可能重命名 R 中的一批列名,只更改一个数字,使名称的 rest 保持不变?

[英]How could one rename a batch of column names in R and change only one digit, leaving the rest of the name the same?

I have data from one survey with 30 items collected over two waves (ie, time points).我有来自一项调查的数据,其中包含在两个波(即时间点)上收集的 30 个项目。 Items are labeled as follows: item1w1, item2w1, item3w1, etc., where w1 = wave 1. How can I rename all items by only changing the w1 to w2, leaving the rest of the item name the same as the original, without changing each item individually, as with dplyr::rename or some other method?项目标记如下:item1w1,item2w1,item3w1等,其中w1 = wave 1。如何通过仅将w1更改为w2来重命名所有项目,而项目名称的rest与原始名称相同,无需更改每个项目单独,如 dplyr::rename 或其他方法?

That is, item1 w1 = item1 w2 , item2 w1 = item2 w2 , etc.也就是说, item1 w1 = item1 w2 , item2 w1 = item2 w2 ,等等。

Using base R使用base R

names(df) <- sub("w1$", "w2", names(df))

You can use rename_with :您可以使用rename_with

library(dplyr)
rename_with(your_dataframe, ~ gsub("w1", "w2", .x), ends_with("w1"))
#alternative:
#rename_with(your_dataframe, ~ gsub("w1$", "w2", .x))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM