在尝试时aggregate
另一个问题here https://stackoverflow.com/questions/14434632/find-frequency-of-each-unique-column-in-a-matrix-or-data-frame/14436500#14436500,我遇到了一个相当奇怪的结果。我无法弄清楚为什么,并且想知道我所做的是否完全错误。
假设,我有一个data.frame
像这样:
df <- structure(list(V1 = c(1L, 2L, 1L, 2L, 3L, 1L),
V2 = c(2L, 3L, 2L, 3L, 4L, 2L),
V3 = c(3L, 4L, 3L, 4L, 5L, 3L),
V4 = c(4L, 5L, 4L, 5L, 6L, 4L)),
.Names = c("V1", "V2", "V3", "V4"),
row.names = c(NA, -6L), class = "data.frame")
> df
# V1 V2 V3 V4
# 1 1 2 3 4
# 2 2 3 4 5
# 3 1 2 3 4
# 4 2 3 4 5
# 5 3 4 5 6
# 6 1 2 3 4
现在,如果我想输出一个data.frame
with 独特的行还有一列表明它们的频率df
。对于这个例子,
# V1 V2 V3 V4 x
# 1 1 2 3 4 3
# 2 2 3 4 5 2
# 3 3 4 5 6 1
我使用获得此输出aggregate
通过如下实验:
> aggregate(do.call(paste, df), by=df, print)
# [1] "1 2 3 4" "1 2 3 4" "1 2 3 4"
# [1] "2 3 4 5" "2 3 4 5"
# [1] "3 4 5 6"
# V1 V2 V3 V4 x
# 1 1 2 3 4 1 2 3 4, 1 2 3 4, 1 2 3 4
# 2 2 3 4 5 2 3 4 5, 2 3 4 5
# 3 3 4 5 6 3 4 5 6
所以,这给了我粘贴的字符串。所以,如果我要使用length
代替print
,它应该给我出现这种情况的次数,这是期望的结果,就是这种情况(如下所示)。
> aggregate(do.call(paste, df), by=df, length)
# V1 V2 V3 V4 x
# 1 1 2 3 4 3
# 2 2 3 4 5 2
# 3 3 4 5 6 1
这似乎有效。然而,当data.frame
尺寸为4*2500,输出data.frame
是 1*2501 而不是 4*2501(所有行都是唯一的,因此频率为 1)。
> df <- as.data.frame(matrix(sample(1:3, 1e4, replace = TRUE), nrow=4))
> o <- aggregate(do.call(paste, df), by=df, length)
> dim(o)
# [1] 1 2501
我用较小的 data.frames 进行了测试,只有唯一的行,它给出了正确的输出(改变nrow=40
, 例如)。然而,当矩阵的维度增加时,这似乎不起作用。我就是不明白出了什么问题!有任何想法吗?