如何使用强制转换或其他函数在 R 中创建二进制表 [英] How to use cast or another function to create a binary table in R
本文介绍了如何使用强制转换或其他函数在 R 中创建二进制表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试创建一个具有二元响应并一直在使用强制转换的因素列表.
I am trying to create a list of factors that have a binary response and have been using cast.
DF2 <- cast(data.frame(DM), id ~ region)
names(DF2)[-1] <- paste("region", names(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)
结果:
id region1 region2 region3
1 1 0 1 1
2 2 0 1 0
3 3 1 0 0
这篇关于如何使用强制转换或其他函数在 R 中创建二进制表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文