簡體   English   中英

使用兩個變量創建計數矩陣

[英]Create matrix of counts using two variables

我有兩列-唯一的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或使用基數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")

更容易了解字符變量的情況

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

 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM