如何生成 R 计数矩阵 [英] How to produce an R count matrix

查看:21
本文介绍了如何生成 R 计数矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 R 中,我可以使用我感兴趣的特定列名作为数组返回计数结果,如下所示.

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:显然,解决方案不需要使用plyr.

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

推荐答案

您需要一个列联表,可以使用 table 创建:

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

这篇关于如何生成 R 计数矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆