如何使用cast或另一个函数在R中创建二进制表 [英] How to use cast or another function to create a binary table in R

查看:113
本文介绍了如何使用cast或另一个函数在R中创建二进制表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建一个具有二进制响应并且已使用cast的因子列表。

I am trying to create a list of factors that have a binary response and have been using cast.

DF2 <数据框(DM),id_区域)
名称(DF2)[-1] < - 粘贴(region,名称(DF2)[ - 1],sep =)

我得到的问题是响应是答案出现的频率,而我正在寻找是否匹配。

The problem I am getting is that the responses are the frequency of which the answer comes up, while I'm looking for just whether or not it matches.

例如我有:

id region
 1   2
 1   3
 2   2
 3   1
 3   1

我想要的是:

id region1 region2 region3
1   0          1     1
2   0          1     0
3   1          0     0


推荐答案

原始资料:

x <- data.frame(id=c(1,1,2,3,3), region=factor(c(2,3,2,1,1)))

> x
  id region
1  1      2
2  1      3
3  2      2
4  3      1
5  3      1

分组数据:

aggregate(model.matrix(~ region - 1, data=x), x["id"], max)


$ b b

结果:

Result:

  id region1 region2 region3
1  1       0       1       1
2  2       0       1       0
3  3       1       0       0

这篇关于如何使用cast或另一个函数在R中创建二进制表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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