在旧列名称中按字符串ID更改列名称

时间:2017-04-19 21:13:01

标签: r dataframe col

考虑我在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的列的数量以及位置都在变化。非常感谢!

2 个答案:

答案 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))