我有一个非常大的矩阵,我知道其中一些列名是重复的。因此,我想找到这些重复的列名并从中删除一个列。
我尝试了duplicate()
,但它只会删除重复的条目。
有人能帮我在R中实现这个功能吗?
关键是,重复列名可能没有重复的条目。
我有一个非常大的矩阵,我知道其中一些列名是重复的。因此,我想找到这些重复的列名并从中删除一个列。
我尝试了duplicate()
,但它只会删除重复的条目。
有人能帮我在R中实现这个功能吗?
关键是,重复列名可能没有重复的条目。
假设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
或者假设你正在处理数据框,你可以使用 subset
:
subset(iris, select=which(!duplicated(names(.))))
请注意,dplyr::select
在这里不适用,因为它要求输入数据中的列具有唯一性。iris <- iris %>% subset(., select = which(!duplicated(names(.))))
的管道友好版本为: iris <- iris %>% distinct()
。 - seapenwhich
。如果没有dplyr
,正确的版本是subset(iris, select = !duplicated(names(iris)))
。 - Maëltemp = 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)
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))]
# 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]
which(duplicated(colnames(food)))
。 - user3932000
列名
但相同的值
,重复的只是名称不同。我们该如何处理呢? - Roy