2015-12-18 18 views
5

Ho un frame di dati, che sembra qualcosa di simile:Creare una matrice frequenza bimodale 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 

Ci sono oltre 400 variabili dell'insieme di dati. Questo è solo un esempio. Devo creare una matrice di frequenza semplice in R (esclusi i numeri del caso), ma la funzione table non funziona. In particolare, sto cercando di cross-tabulare una porzione delle colonne per creare una matrice di frequenze a due modalità. La tabella dovrebbe essere così:

 Var1 Var2 
Resp1 3  1 
Resp2 3  2 

Nel Stata, il comando è:

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 

risposta

5

Questo uno dovrebbe funzionare per qualsiasi numero di Var & Respe:

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] Una versione più elegante, a condizione che nel commento di G.Grothendieck:

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

Una ulteriore semplificazione sarebbe 'm <- as.matrix (d) dal momento che i' greps non potrà mai corrispondere alla prima colonna in ogni modo. –

+0

Grazie! Questo è così utile. Come faccio a fare riferimento ai numeri delle colonne, piuttosto che ai nomi delle colonne, usando il comando crossprod? – jj987246

+0

@ jj987246, è sufficiente utilizzare i vettori contenenti i numeri di colonna, ad es. 'Crossprod (m [, 1: 4], m [, 5: 8])' –

4

Sono sicuro che c'è un altro modo, ma si potrebbe fare questo:

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 
3

Ecco un approccio usando 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 

dati di esempio:

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) 
Problemi correlati