数据框中非唯一元素的索引

时间:2016-05-22 17:05:17

标签: r

如何在下一个数据框中提取重复元素的列名(或行索引和列索引)?

            V1         V2           V3           V4
PC1  0.5863431  0.5863431 3.952237e-01 3.952237e-01
PC2 -0.3952237 -0.3952237 5.863431e-01 5.863431e-01
PC3 -0.7071068  0.7071068 1.665335e-16 3.885781e-16

例如,0.5863431等于0.5863431,因此"V1""V2"是列名。

在我希望获得的数据框中:

[1] "V1" "V2" "V3" "V4"

如你所见,只看第一行的结果。

第二个例子:

            V1         V2          V3         V4
PC1 -0.5987139 -0.5987139 -0.03790446  0.5307039
PC2 -0.0189601 -0.0189601 -0.99315168 -0.1137136
PC3  0.3986891  0.3523926 -0.11045319  0.8394442

结果:

[1] "V1" "V2"

3 个答案:

答案 0 :(得分:8)

可能有更好的方法,但这是我的看法。

.active

示例:在您的第一个数据框中 -

## coerce to matrix (if not already)
m <- as.matrix(df)
## find duplicates across both margins
d <- duplicated(m, MARGIN = 0) | duplicated(m, MARGIN = 0, fromLast = TRUE)
## grab the unique col names
colnames(m)[unique(col(d)[d])]

在第二个 -

df1 <- read.table(text = "V1         V2           V3           V4
PC1  0.5863431  0.5863431 3.952237e-01 3.952237e-01
PC2 -0.3952237 -0.3952237 5.863431e-01 5.863431e-01
PC3 -0.7071068  0.7071068 1.665335e-16 3.885781e-16", header = TRUE)

m1 <- as.matrix(df1)
d1 <- duplicated(m1, MARGIN = 0) | duplicated(m1, MARGIN = 0, fromLast = TRUE)
colnames(m1)[unique(col(d1)[d1])]
# [1] "V1" "V2" "V3" "V4"

旁注:由于您的数据包含所有数值,我建议您从矩阵而不是数据框开始。

答案 1 :(得分:3)

使用whichapply

的方法略有不同
# convert to matrix
mat1 <- as.matrix(df1)
# find duplicates and store them
dups <- mat1[which(duplicated(c(mat1)))]
# identify columns containing a value in dups
names(which(apply(mat1, 2, function(x) any(x %in% dups))))
#[1] "V1" "V2" "V3" "V4"

mat2 <- as.matrix(df2)
dups <- mat2[which(duplicated(c(mat2)))]
names(which(apply(mat2, 2, function(x) any(x %in% dups))))
#[1] "V1" "V2"

答案 2 :(得分:1)

无论使用何种方法,在使用浮点数时都要注意FAQ 7.31。您可能想要创建一个新矩阵,您可以将它们“舍入”到相同的位数;虽然它们可能在打印输出上“看起来”相同,但在尾随数字中可能会出现差异。