简体   繁体   English

在R中创建双模频率矩阵

[英]Create a two-mode frequency matrix in 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

There are over 400 variables in the dataset. 数据集中有400多个变量。 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. 我需要在R中创建一个简单的频率矩阵(不包括案例编号),但table函数不起作用。 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

In Stata, the command is: 在Stata中,命令是:

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

This one should work for any number of Var & Resps: 这个适用于任何数量的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] A more elegant version, provided in the comment by G.Grothendieck: [更新] G.Grothendieck的评论中提供了一个更优雅的版本:

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

I'm sure there's another way, but you could do this: 我确定还有另一种方法,但你可以这样做:

library(reshape2)
library(plyr)

df1 <- melt(df[,-1],id=1:2)
ddply(df1,.(variable),summarize,
      Var1 = sum(value==1&Var1==1),
      Var2 = sum(value==1&Var2==1))

#   variable Var1 Var2
# 1    Resp1    3    1
# 2    Resp2    3    2

Here is an approach using xtabs . 这是一种使用xtabs的方法。

# get names of non "variables"
not_vars <- c("Resp1", "Resp2", "CASENO")

# get names of "variables"
vars <- as.matrix(d[,!names(d) %in% not_vars])

# if you have many more than 2 response variables, this could get unwieldy
result <- rbind(
    xtabs( vars ~ Resp1, data=d, exclude=0),
    xtabs( vars ~ Resp2, data=d, exclude=0))

# give resulting table appropriate row names.    
rownames(result) <- c("Resp1", "Resp2")
#      Var1 Var2
#Resp1    3    1
#Resp2    3    2

sample data: 样本数据:

d <- read.table(text="
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", header=TRUE)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM