How to produce an R count matrix

▼魔方 西西 提交于 2019-11-30 21:04:12

问题


In R, I can return the count results using the specific column names I am interested in as an array as below.

require("plyr")
bevs <- data.frame(cbind(name = c("Bill", "Llib"), drink = c("coffee", "tea", "cocoa", "water"), cost = seq(1:8)))
count(bevs, c("name", "drink"))

# produces
  name  drink freq
1 Bill  cocoa    2
2 Bill coffee    2
3 Llib    tea    2
4 Llib  water    2

How can I get the count result of two specific column names in a matrix which has columns: all unique drinks, rows: all unique names and cells: freqs (like below)?

     cocoa  coffee tea water
Bill   2      2     0   0
Llib   0      0     2   2

P.S: Obviously, the solution does not need to use plyr.


回答1:


You want a contingency table, which you can create using table:

table(bevs[, c("name", "drink")])
#      drink
#name   cocoa coffee tea water
#  Bill     2      2   0     0
#  Llib     0      0   2     2


来源:https://stackoverflow.com/questions/20044744/how-to-produce-an-r-count-matrix

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!