查找数据框中的唯一组合数和每个组合中的观察数
Find number of unique combinations in data frame and Number of observations in each combination
这个问题来自 a previous question。如果我们有三列或更多列,而不是两列呢?考虑以下数据。
x <- c(600, 600, 600, 600, 600, 600, 600, 600, 600, 800, 800, 800, 800, 800, 800, 800, 800, 800,
600, 600, 600, 600, 600, 600, 600, 600, 600, 800, 800, 800, 800, 800, 800, 800, 800, 800,
600, 600, 600, 600, 600, 600, 600, 600, 600, 800, 800, 800, 800, 800, 800, 800, 800, 800)
y <- c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3)
z <- c(1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3,
1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3,
1, 2, 3, 1, 2, 3)
xyz <- data.frame(cbind(x, y, z))
如果我们将所有列都视为具有有限级数的因子。我想要得到的是 x、y 和 z 的每个唯一组合中的观察次数。答案是 18 个独特的组合,每个组合有 3 个观察值。请问我怎样才能在 R 中做到这一点?谢谢!
使用 table
或 tabulate
与 interaction
tabulate(with(xyz, interaction(x,y,z)))
table(with(xyz, interaction(x,y,z)))
或split
通过交互和使用lengths
,
lengths(split(xyz, with(xyz, interaction(x,y,z))))
或
aggregate(seq_along(x)~ x+y+z, data=xyz, FUN=length)
使用 data.table
的选项。我们将'data.frame'转换为'data.table'(setDT(xyz)
,按'xyz'的列分组,得到每组的元素个数(.N
)
library(data.table)
setDT(xyz)[, .N, names(xyz)]$N
#[1] 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3
或使用 dplyr
,我们按列分组,使用 summarise
.
获取元素数 (n()
)
library(dplyr)
xyz %>%
group_by_(.dots=names(xyz)) %>%
summarise(n=n()) %>%
.$n
#[1] 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3
这个问题来自 a previous question。如果我们有三列或更多列,而不是两列呢?考虑以下数据。
x <- c(600, 600, 600, 600, 600, 600, 600, 600, 600, 800, 800, 800, 800, 800, 800, 800, 800, 800,
600, 600, 600, 600, 600, 600, 600, 600, 600, 800, 800, 800, 800, 800, 800, 800, 800, 800,
600, 600, 600, 600, 600, 600, 600, 600, 600, 800, 800, 800, 800, 800, 800, 800, 800, 800)
y <- c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3)
z <- c(1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3,
1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3,
1, 2, 3, 1, 2, 3)
xyz <- data.frame(cbind(x, y, z))
如果我们将所有列都视为具有有限级数的因子。我想要得到的是 x、y 和 z 的每个唯一组合中的观察次数。答案是 18 个独特的组合,每个组合有 3 个观察值。请问我怎样才能在 R 中做到这一点?谢谢!
使用 table
或 tabulate
与 interaction
tabulate(with(xyz, interaction(x,y,z)))
table(with(xyz, interaction(x,y,z)))
或split
通过交互和使用lengths
,
lengths(split(xyz, with(xyz, interaction(x,y,z))))
或
aggregate(seq_along(x)~ x+y+z, data=xyz, FUN=length)
使用 data.table
的选项。我们将'data.frame'转换为'data.table'(setDT(xyz)
,按'xyz'的列分组,得到每组的元素个数(.N
)
library(data.table)
setDT(xyz)[, .N, names(xyz)]$N
#[1] 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3
或使用 dplyr
,我们按列分组,使用 summarise
.
n()
)
library(dplyr)
xyz %>%
group_by_(.dots=names(xyz)) %>%
summarise(n=n()) %>%
.$n
#[1] 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3