我有一個資料框,如果您看不到其他列,某些列名將不清楚。例如列“blue1”。這意味著設計師 Mal 的藍色椅子將花費 5 美元。
data.frame(designer = c("mal", "didi", "yels", "don"),
trashcan = c(1:4),
chair = c(1:4), blue1 = c(5:8), yellow2 = c(6:9), orange3 = c(11:14),
bedframe = c(5:8), blue4 = c(6:9), yellow5 = c(11:14), orange6 = c(16:19))
# designer trashcan chair blue1 yellow2 orange3 bedframe blue4 yellow5 orange6
# 1 mal 1 1 5 6 11 5 6 11 16
# 2 didi 2 2 6 7 12 6 7 12 17
# 3 yels 3 3 7 8 13 7 8 13 18
# 4 don 4 4 8 9 14 8 9 14 19
# would like to get
# designer trashcan chair blue1_chair yellow2_chair orange3_chair bedframe blue4_bedframe yellow5_bedframe orange6_bedframe
# 1 mal 1 1 5 6 11 5 6 11 16
# 2 didi 2 2 6 7 12 6 7 12 17
# 3 yels 3 3 7 8 13 7 8 13 18
# 4 don 4 4 8 9 14 8 9 14 19
要知道的事情:
- 一件家具總是有 0 或 3 種其他顏色(垃圾桶有 0 種其他顏色)。
- 3 種顏色總是直接出現在它所涉及的家具之后。
- 顏色后面的數字可以是隨機的
有什么建議?
uj5u.com熱心網友回復:
我們可以分兩步執行此操作,rename_with其中第一個matches是“藍色”、“黃色”、“橙色”,后跟 1,第二個匹配相同的前綴,后跟 2,然后粘貼“_chair”、“_bedframe”分別
library(dplyr)
library(stringr)
df1 <- df1 %>%
rename_with(~ str_c(.x, "_chair"), matches("^(blue|yellow|orange)[0-3]$")) %>%
rename_with(~ str_c(.x, "_bedframe"),
matches("^(blue|yellow|orange)[4-6]$"))
-輸出
df1
designer trashcan chair blue1_chair yellow2_chair orange3_chair bedframe blue4_bedframe yellow5_bedframe orange6_bedframe
1 mal 1 1 5 6 11 5 6 11 16
2 didi 2 2 6 7 12 6 7 12 17
3 yels 3 3 7 8 13 7 8 13 18
4 don 4 4 8 9 14 8 9 14 19
或另一種選擇base R
nm1 <- names(df1)[3:ncol(df1)]
i1 <- !grepl('\\d $', nm1)
i2 <- cumsum(i1)
names(df1)[-(1:2)] <- ave(nm1, i2, FUN = function(x)
replace(x, -1, paste0(x[-1], "_", x[1])))
-輸出
> df1
designer trashcan chair blue1_chair yellow2_chair orange3_chair bedframe blue4_bedframe yellow5_bedframe orange6_bedframe
1 mal 1 1 5 6 11 5 6 11 16
2 didi 2 2 6 7 12 6 7 12 17
3 yels 3 3 7 8 13 7 8 13 18
4 don 4 4 8 9 14 8 9 14 19
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/431693.html
