计算数据表中值组合的出现次数

时间:2015-12-12 15:51:35

标签: r data.table

这是我想要以有效的方式实现的目标: 我有两个数据帧(datacombinations)。 combinations包含来自data的某些变量的特定组合。例如:

combinations:
age       size
50        178
35        180
37        168

data中,我拥有包含各种变量的所有数据集,因此:

data:
id     age     size     name     income      ...
...    ...     ...      ...      ...         ...

我想知道的是以下内容:我想浏览combinations中的每一行,以检查data中变量组合是否以及发生的频率。

所以结果应该是这样的:

age       size    count
50        178     10    # this combination occured 10 times in data
35        180     2
37        168     5 

不幸的是,我似乎找不到办法做到这一点。我非常感谢任何帮助。谢谢!

1 个答案:

答案 0 :(得分:1)

我们可以将tablemerge

一起使用
 merge(as.data.frame(table(data[c('age', 'size')])), combinations)
 #  age size Freq
 #1  35  180    2
 #2  37  168    1
 #3  50  178    2

数据

combinations <- structure(list(age = c(50L, 35L, 37L), 
size = c(178L, 180L, 168L
)), .Names = c("age", "size"), class = "data.frame", 
row.names = c(NA, -3L))

data <- structure(list(id = 1:9, age = c(50L, 35L, 37L, 50L, 
51L, 35L, 
38L, 42L, 53L), size = c(178L, 180L, 168L, 178L, 125L, 180L, 
124L, 134L, 129L), name = c("A", "B", "C", "A", "C", "B", "D", 
"E", "F"), income = c(20L, 25L, 30L, 20L, 33L, 25L, 43L, 29L, 
39L)), .Names = c("id", "age", "size", "name", "income"), 
class = "data.frame", row.names = c(NA, -9L))
相关问题