如何在r中选择特定列并删除,然后在其末尾添加字符串

如何在r中选择特定列并删除,然后在其末尾添加字符串,r,string,dplyr,multiple-columns,rename,R,String,Dplyr,Multiple Columns,Rename,我有一个非常大的数据集,包含三波数据。我想对列名进行标准化,以便波浪名称位于每个变量的末尾。我成功地做到了这一点,但我正在寻找一种更简洁的方法来做到这一点。我的数据如下所示: toy <- as.data.frame(cbind(c(sample(1:100, 5)), c(sample(1:100, 5)), c(sample(1:100, 5)),

我有一个非常大的数据集,包含三波数据。我想对列名进行标准化,以便波浪名称位于每个变量的末尾。我成功地做到了这一点,但我正在寻找一种更简洁的方法来做到这一点。我的数据如下所示:

toy <- as.data.frame(cbind(c(sample(1:100, 5)),
                           c(sample(1:100, 5)),
                           c(sample(1:100, 5)),
                           c(sample(1:100, 5)),
                           c(sample(1:100, 5)),
                           c(sample(1:100, 5))))
colnames(toy) <- c(paste0(LETTERS[1:4], "w", c(1,1,2,2)))
colnames(toy)[c(5,6)] <- c(paste0("w3", LETTERS[5:6]))
我希望它是这样的,第三个波的格式与其他两个一样:

  Aw1 Bw1 Cw2 Dw2 Ew3 Fw3
1  49  23  66  20  34  76
2  50  75  69  21  47  41
3  88  61  19  77  45   7
4  79  94  48  19  61  23
5  83  17  79  35  14  21
这就是我所做的工作:

t1.toy <- toy %>% rename_at(vars(contains("w3")),
                  .funs = list(function(x) paste0(x, "temp")))
t2.toy <- t1.toy %>% rename_at(vars(contains("w3")),
                            .funs = list(function(x) gsub(x = x, 
                                                          pattern = "w3", 
                                                          replacement = "")))
t3.toy <- t2.toy %>% rename_at(vars(contains("temp")),
                               .funs = list(function(x) gsub(x = x, 
                                                             pattern = "temp", 
                                                             replacement = "w3")))

t1.toy%rename_at(vars(包含(“w3”)),
.funs=列表(函数(x)粘贴0(x,“临时”))
t2.2%重命名_at(变量(包含(“w3”)),
.funs=list(函数x)gsub(x=x,
pattern=“w3”,
替换=”))
t3.5%重命名为(变量(包含(“临时”)),
.funs=list(函数x)gsub(x=x,
pattern=“temp”,
替换(“w3”)))

还有其他更快的方法吗?

可能是我们需要作为一个团队进行捕获

library(dplyr)
library(stringr)
toy %>% 
   rename_at(vars(contains('w3')), ~ str_replace(., '(.*\\d+)(.*)', "\\2\\1"))
#  Aw1 Bw1 Cw2 Dw2 Ew3 Fw3
#1  49  23  66  20  34  76
#2  50  75  69  21  47  41
#3  88  61  19  77  45   7
#4  79  94  48  19  61  23
#5  83  17  79  35  14  21

或者,如果需要自动执行此操作,我们可以使用
rename\u all

toy %>%
    rename_all(~ str_replace(., "^([a-z]\\w+)([A-Z])$", "\\2\\1"))
数据
toy您可以使用
colnames

colnames(toy) <- gsub("^(w3)(.+)$", "\\2\\1", colnames(toy))

也许你可以使用下面的代码

toy <- `names<-`(toy,gsub("(.*?\\d+)(.*)","\\2\\1",names(toy)))
toy@garsimpitoyable
(.*?\\d+)
匹配字母后面跟数字的情况,
(.*)
表示字母后面的字符。这里,
(.*?\\d+)
(.*)
对应于
\\1
\\2
。在
gsub()
colnames(toy) <- gsub("^(w3)(.+)$", "\\2\\1", colnames(toy))
  Aw1 Bw1 Cw2 Dw2 Ew3 Fw3
1  49  23  66  20  34  76
2  50  75  69  21  47  41
3  88  61  19  77  45   7
4  79  94  48  19  61  23
5  83  17  79  35  14  21

toy <- `names<-`(toy,gsub("(.*?\\d+)(.*)","\\2\\1",names(toy)))