在R中创建一个双模频率矩阵 [英] Create a two-mode frequency matrix in R

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

问题描述

我有一个数据框,看起来像这样:

I have a data frame, which looks something like this:

CASENO    Var1   Var2   Resp1   Resp2
1          1      0      1      1
2          0      0      0      0
3          1      1      1      1
4          1      1      0      1
5          1      0      1      0

数据集中有超过400个变量.这只是一个例子.我需要在R中创建一个简单的频率矩阵(不包括案例编号),但是table函数不起作用.具体来说,我正在寻找对一部分色谱柱进行交叉制表的方法,以创建频率的双模矩阵.该表应如下所示:

There are over 400 variables in the dataset. This is just an example. I need to create a simple frequency matrix in R (excluding the case numbers), but the table function doesn't work. Specifically, I'm looking to cross-tabulate a portion of the columns to create a two-mode matrix of frequencies. The table should look like this:

       Var1    Var2
Resp1    3       1
Resp2    3       2

在Stata中,命令为:

In Stata, the command is:

gen var = 1 if Var1==1
replace var= 2 if Var2==1

gen resp = 1 if Resp1==1
replace resp = 2 if Resp2==1

tab var resp

推荐答案

该版本适用于任意数量的Var& amp;代表:

This one should work for any number of Var & Resps:

d <- structure(list(CASENO = 1:5, Var1 = c(1L, 0L, 1L, 1L, 1L), Var2 = c(0L,  0L, 1L, 1L, 0L), Resp1 = c(1L, 0L, 1L, 0L, 1L), Resp2 = c(1L,  0L, 1L, 1L, 0L)), .Names = c("CASENO", "Var1", "Var2", "Resp1", "Resp2"), class = "data.frame", row.names = c(NA, -5L))   

m <- as.matrix(d[,-1])
m2 <- t(m) %*% m
rnames <- grepl('Resp',rownames((m2)))
cnames <- grepl('Var',colnames((m2)))
m2[rnames,cnames]

[UPDATE]一个更优雅的版本,由G.Grothendieck的评论提供:

[UPDATE] A more elegant version, provided in the comment by G.Grothendieck:

m <- as.matrix(d[,-1])
cn <- colnames(m); 
crossprod(m[, grep("Resp", cn)], m[, grep("Var", cn)])

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

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