如何重命名重复名称的名字(或n)?

时间:2019-05-22 03:26:21

标签: r

我的data.frame

data <- structure(list(X1 = c(59.8762607388198, 67.1632845699787, 23.6637377925217, 
69.9449949897826, 35.2058596163988, 38.1956151127815), X2 = c(62.1132328920066, 
21.8021914549172, 61.9988731481135, 34.3215084075928, 80.3957843966782, 
60.5674904584885), X3 = c(88.2267396338284, 59.4003888778389, 
73.828971683979, 66.0273016430438, 23.343755248934, 36.3777917064726
), X4 = c(48.4459692239761, 40.9731803461909, 99.6187647990882, 
36.7934556119144, 59.0364990569651, 75.4534260369837), X5 = c(73.2776108942926, 
97.464852463454, 95.126473121345, 52.8497830219567, 60.7845875620842, 
65.9690665081143), X6 = c(38.557508662343, 87.049773093313, 74.7623572312295, 
77.6170065626502, 98.8315769098699, 91.4291994087398), clusters = c(1L, 
3L, 2L, 3L, 2L, 1L), group = structure(c(3L, 3L, 2L, 3L, 2L, 
2L), .Label = c("1", "2", "3"), class = "factor"), clusters = structure(c(3L, 
3L, 2L, 3L, 2L, 2L), .Label = c("cluster_1", "cluster_2", "cluster_3"
), class = "factor")), .Names = c("X1", "X2", "X3", "X4", "X5", 
"X6", "clusters", "group", "clusters"), row.names = c(NA, 6L), class = "data.frame")
names(data)

[1] "X1"       "X2"       "X3"       "X4"       "X5"       "X6"       "clusters" "group"   
[9] "clusters"

data包含称为clusters的两列。如何分别重命名?

grep函数同时重命名两者:

names(data)[grep(pattern = 'clus', ignore.case = TRUE, x = colnames(data))] <- 'cluster_1'

[1] "X1"       "X2"       "X3"       "X4"       "X5"       "X6"       "cluster_1" "group"   
[9] "cluster_1"

1 个答案:

答案 0 :(得分:2)

一个更简单的选择是make.unique,将重复的列名称更改为unique名称

names(data) <- make.unique(names(data))