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

如何删除R中重复的列名?,r,R,我有一个很大的矩阵,我知道它们的一些名字是重复的。所以我只想找到那些重复的colname,并从duplicate中删除列的on。 我尝试复制,但它删除了重复的条目。 有人能帮我在R中实现这一点吗? 关键是,重复的colname可能没有重复的entires。假设temp是您的矩阵 temp <- matrix(seq_len(15), 5, 3) colnames(temp) <- c("A", "A", "B") ## A A B ## [1,] 1 6 11 ##

我有一个很大的矩阵,我知道它们的一些名字是重复的。所以我只想找到那些重复的colname,并从duplicate中删除列的on。 我尝试复制,但它删除了重复的条目。 有人能帮我在R中实现这一点吗? 关键是,重复的colname可能没有重复的entires。

假设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

或者假设data.frames可以使用子集:


请注意,dplyr::select在这里不适用,因为它已经要求输入数据中的列唯一性

将所有重复项存储到一个向量中,例如重复项,并使用带单括号子集的-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]

要按名称删除特定的重复列,可以执行以下操作:

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]
或:


对重复的列编号进行硬编码不是很好。更好、更灵活的做法是使用复制的名称来代替。iris%subset.,select=which!重复的名字。管道友好型版本为什么要将其转换为数据帧,然后再转换回矩阵?这和我的回答有什么不同?你不需要写一个额外的逗号吗?这很重要,因为我的解决方案是data.table data.frame,所以我无法让你的解决方案工作。有一次我把它转换成了矩阵,工作起来很有魅力。逗号省略是偶然的,不会影响任何事情。
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))]
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)