如何在R中建立频率矩阵? [英] How to build frequency matrix in R?

查看:226
本文介绍了如何在R中建立频率矩阵?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设名为 A 的现有数据框包含以下数据:

Suppose that the existing data frame named as A contains the following data:

Time    Var
T1      loc1
T1      loc2
T1      loc3
T2      loc2
T2      loc2
T2      loc3
T3      loc1
T3      loc3
T3      loc3

在下面我想要R中的输出频率矩阵格式

I want the output frequency matrix in R in the following format

      loc1    loc2    loc3
T1     1       1       1
T2     0       2       1
T3     1       0       2

我尝试使用 apply() table(),但无法理解如何使用它们来获取所需的输出。
有人可以建议我使用R中的某些函数来获取所需的输出吗?

I tried using apply(), table() but could not understand how to use them to get my required output. Can somebody suggest me some functions in R which I can use to get the required output?

推荐答案

您可以在基础R中使用 xtabs

You could go for xtabs in base R

xtabs(~Time+Var, A)

#    Var
#Time loc1 loc2 loc3
#  T1    1    1    1
#  T2    0    2    1
#  T3    1    0    2






dcast 来自 data.table

library(data.table)
dcast(A, Time~Var)

这篇关于如何在R中建立频率矩阵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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