如何在R中删除重复的列名?

33

我有一个非常大的矩阵,我知道其中一些列名是重复的。因此,我想找到这些重复的列名并从中删除一个列。 我尝试了duplicate(),但它只会删除重复的条目。 有人能帮我在R中实现这个功能吗? 关键是,重复列名可能没有重复的条目。

5个回答

57

假设temp是您的矩阵

temp <- matrix(seq_len(15), 5, 3)
colnames(temp) <- c("A", "A", "B")

##      A  A  B
## [1,] 1  6 11
## [2,] 2  7 12
## [3,] 3  8 13
## [4,] 4  9 14
## [5,] 5 10 15

你可以这样做

temp <- temp[, !duplicated(colnames(temp))]

##      A  B
## [1,] 1 11
## [2,] 2 12
## [3,] 3 13
## [4,] 4 14
## [5,] 5 15

或者,如果你想保留最后一个重复的列,可以这样做:

temp <- temp[, !duplicated(colnames(temp), fromLast = TRUE)] 

##       A  B
## [1,]  6 11
## [2,]  7 12
## [3,]  8 13
## [4,]  9 14
## [5,] 10 15

嗨@david-arenburg。感谢你提供的如此有用的解决方案。如果一个数据框具有两列不同的列名但相同的,重复的只是名称不同。我们该如何处理呢? - Roy

18

或者假设你正在处理数据框,你可以使用 subset

subset(iris, select=which(!duplicated(names(.)))) 
请注意,dplyr::select 在这里不适用,因为它要求输入数据中的列具有唯一性。

3
iris <- iris %>% subset(., select = which(!duplicated(names(.))))的管道友好版本为: iris <- iris %>% distinct() - seapen
不需要在这里使用which。如果没有dplyr,正确的版本是subset(iris, select = !duplicated(names(iris))) - Maël

3
temp = matrix(seq_len(15), 5, 3)
colnames(temp) = c("A", "A", "B")

temp = as.data.frame.matrix(temp)
temp = temp[!duplicated(colnames(temp))]
temp = as.matrix(temp)

为什么将它转换为数据框再转回矩阵?这与我的答案有何不同?你不需要写额外的逗号吗? - David Arenburg
这很重要,因为我无法使您的解决方案工作,因为我的数据是一个data.table数据框。一旦我将其转换为矩阵,它就像魔术般地工作了。逗号的省略是偶然的,不会影响任何事情。 - Arani

1
要按名称删除特定重复列,您可以执行以下操作:
test = cbind(iris, iris) # example with multiple duplicate columns
idx = which(duplicated(names(test)) & names(test) == "Species")
test = test[,-idx]

为了删除所有重复的列,操作稍微简单一些:
test = cbind(iris, iris) # example with multiple duplicate columns
idx = which(duplicated(names(test)))
test = test[,-idx]

或者:

test = cbind(iris, iris) # example with multiple duplicate columns
test = test[,!duplicated(names(test))]

0
将所有重复的列存储到一个向量中,比如说duplicates,并使用-duplicates和单括号子集来删除重复的列。
       # Define vector of duplicate cols (don't change)
       duplicates <- c(4, 6, 11, 13, 15, 17, 18, 20, 22, 
            24, 25, 28, 32, 34, 36, 38, 40, 
            44, 46, 48, 51, 54, 65, 158)

      # Remove duplicates from food and assign it to food2
         food2 <- food[,-duplicates]

2
不应该硬编码重复的列编号,更好和更灵活的做法是使用which(duplicated(colnames(food))) - user3932000

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接