使用两个变量创建计数矩阵

问题描述:

我有两列 - 唯一ID列id和旅行当天day。我的目标是创建每天每ID计数的矩阵(即使计数为零包括所有天)使用两个变量创建计数矩阵

> test 
    id day 
1 3 3 
2 4 4 
3 1 4 
4 2 3 
5 2 5 
6 2 4 
7 1 1 
8 5 4 
9 1 1 
10 3 2 
11 2 2 
12 4 2 
13 2 4 
14 2 5 
15 4 5 
16 3 4 
17 5 3 
18 3 2 
19 5 5 
20 3 4 
21 1 3 
22 2 3 
23 2 5 
24 5 2 
25 3 2 

输出应该是以下,其中行表示id和列代表day

> output 
    1 2 3 4 5 
1 2 0 1 1 0 
2 0 1 2 2 3 
3 0 3 1 2 0 
4 0 1 0 1 1 
5 0 1 1 1 1 

我曾尝试与reshape

output <- reshape2::dcast(test, day ~ id, sum) 

以下,但它引发以下错误:

Error in unique.default(x) : unique() applies only to vectors 

为什么会发生这种情况,dplyr或使用base R的正确解决方案是什么?任何提示将不胜感激。

下面是数据:

> dput(test) 
structure(list(id = c(3, 4, 1, 2, 2, 2, 1, 5, 1, 3, 2, 4, 2, 
2, 4, 3, 5, 3, 5, 3, 1, 2, 2, 5, 3), day = c(3, 4, 4, 3, 5, 4, 
1, 4, 1, 2, 2, 2, 4, 5, 5, 4, 3, 2, 5, 4, 3, 3, 5, 2, 2)), .Names = c("id", 
"day"), row.names = c(NA, -25L), class = "data.frame") 
+6

'table(d)'应该给你你想要的输出。 – Lamia

+0

当然这是重复的。 –

ans <- tapply(test$id, test$day, 
       function(x) { 
       y <- table(x) 
       z <- rep(0, 5) 
       z[as.numeric(names(y))] <- y 
       z 
       }) 
do.call("cbind", ans) 
    1 2 3 4 5 
[1,] 2 0 1 1 0 
[2,] 0 1 2 2 3 
[3,] 0 3 1 2 0 
[4,] 0 1 0 1 1 
[5,] 0 1 1 1 1 

更容易

看到什么回事字符变量

id <- c('a', 'a', 'b', 'f', 'b', 'a') 
day <- c('x', 'x', 'x', 'y', 'z', 'x') 

test <- data.frame(id, day) 



output <- as.data.frame.matrix(table(test)) 

这是做最简单的方法......使用table()功能然后转换为data.frame