【发布时间】:2023-11-20 06:46:01
【问题描述】:
我有一个非常大的数据集,包含三波数据。我想标准化列名,以便波浪名称位于每个变量的末尾。我成功地做到了,但我正在寻找一种更简洁的方法来做到这一点。我的数据如下所示:
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")))
还有其他更快的方法吗?
【问题讨论】:
标签: r string dplyr multiple-columns rename