考虑我在R中有一个带有col名称的数据框:
data:
A B C D E V1 V2 V3 V4 V5 V6 Vx...
2 3 4 5 6 5 5 5 5 2 2
我如何获取包含V
的所有值并将其替换为Sample
所以我得到了:
数据:
A B C D E Sample1 Sample2 Sample3 Sample4 Sample5 Sample6 Samplex...
2 3 4 5 6 5 5 5 5 2 2
我需要一个通用的解决方案,因为在我的数据框中,带有V的列的数量以及位置都在变化。非常感谢!
答案 0 :(得分:2)
一个简单的解决方案是使用sub
和 regex 来修改列名,此处^V
匹配字符串开头的字母V
,被Sample
取代:
names(df) <- sub("^V", "Sample", names(df))
df
# A B C D E Sample1 Sample2 Sample3 Sample4 Sample5 Sample6
#1 2 3 4 5 6 5 5 5 5 2 2
答案 1 :(得分:1)
另一个选择是将&#39; V&#39;列名称和数据集上的更新
i1 <- grep("^V", names(df))
names(df)[i1] <- paste0("Sample", seq_along(i1))
df
# A B C D E Sample1 Sample2 Sample3 Sample4 Sample5 Sample6
#1 2 3 4 5 6 5 5 5 5 2 2
df <- structure(list(A = 2L, B = 3L, C = 4L, D = 5L, E = 6L, V1 = 5L,
V2 = 5L, V3 = 5L, V4 = 5L, V5 = 2L, V6 = 2L), .Names = c("A",
"B", "C", "D", "E", "V1", "V2", "V3", "V4", "V5", "V6"),
class = "data.frame", row.names = c(NA, -1L))