我有一个非常大的数据集,包含三波数据。我想标准化列名称,以便波形名称位于每个变量的末尾。我成功地做到了这一点,但正在寻找一种更简洁的方法来做到这一点。我的数据如下所示:
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]))
输出为:
toy
Aw1 Bw1 Cw2 Dw2 w3E w3F
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
我希望它是这样的,其中第三波的格式与其他两个相同:
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")))
还有其他更快的方法吗?
最佳答案
也许你可以使用下面的代码
toy <- `names<-`(toy,gsub("(.*?\\d+)(.*)","\\2\\1",names(toy)))
关于r - 如何在 r 中选择特定列并删除然后在其末尾添加字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59513765/