[英]Create a two-mode frequency matrix in R
我有一個數據框,看起來像這樣:
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
函數不起作用。 具體來說,我希望將一部分列交叉制表以創建雙模頻率矩陣。 該表應如下所示:
Var1 Var2
Resp1 3 1
Resp2 3 2
在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
這個適用於任何數量的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]
[更新] G.Grothendieck的評論中提供了一個更優雅的版本:
m <- as.matrix(d[,-1])
cn <- colnames(m);
crossprod(m[, grep("Resp", cn)], m[, grep("Var", cn)])
我確定還有另一種方法,但你可以這樣做:
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
這是一種使用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
樣本數據:
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.