2014-11-04 40 views
2

我期待爲三個主要效應構建一個應變表。這些都是犯罪,性別和先前的信念。響應變量是否是一個寬鬆的句子被授予。R中的三因子應變表

這是迄今爲止我所見過的最好的。

 Crime Gender Priorconv Yes No 
1  Shoplifting Men   N 24 1 
2 Other Theft Acts Men   N 52 9 
3  Shoplifting Women   N 48 3 
4 Other Theft Acts Women   N 22 2 
5  Shoplifting Men   P 17 6 
6 Other Theft Acts Men   P 60 34 
7  Shoplifting Women   P 15 6 
8 Other Theft Acts Women   P 4 3 

這是由下面的代碼

table1<-expand.grid(Crime=factor(c("Shoplifting","Other Theft Acts")),Gender=factor(c("Men","Women")), 
Priorconv=factor(c("N","P"))) 

table1<-data.frame(table1,Yes=c(24,52,48,22,17,60,15,4),No=c(1,9,3,2,6,34,6,3)) 

創建不幸的是,這是不是很優雅,所以我想知道是否有另一種方式來更清晰地呈現數據。

謝謝。

+1

也許看看'xtabs'和/或' ftable' – 2014-11-04 21:56:33

+0

@DominicComtois我喜歡xtabs的功能。我嘗試使用xtabs(cbind(是,否)〜Crime + Gender + Priorconv,data = table1) – JohnK 2014-11-04 22:16:08

+0

很高興知道!也許你可以發佈代碼和輸出作爲你自己問題的答案。我相信這對你情況下的其他人會有用。 – 2014-11-04 22:27:04

回答

4

應急你可以使用樣品運營商,並把它內部功能改變字符串的數字,如

factory <- function(i) { 
    crime <- sample(c("Shoplifting","Other Theft Acts"),i, replace = TRUE) 
    gender <- sample(c("Men","Women"),i,replace = TRUE) 
    priorconv <- sample(c("P","N"),i, replace = TRUE) 
    table <- data.frame(crime,gender,priorconv) 
    return(table) 
} 
table1 <- factory(20) 

結果:

   crime gender priorconv 
1  Shoplifting Men   N 
2  Shoplifting Women   P 
3 Other Theft Acts Men   P 
4  Shoplifting Men   P 
5 Other Theft Acts Women   N 
6  Shoplifting Women   N 
7  Shoplifting Women   P 
8  Shoplifting Men   P 
9 Other Theft Acts Women   P 
10  Shoplifting Men   P 
11 Other Theft Acts Men   N 
12 Other Theft Acts Men   P 
13  Shoplifting Men   P 
14  Shoplifting Women   N 
15 Other Theft Acts Men   N 
16 Other Theft Acts Men   P 
17 Other Theft Acts Women   P 
18  Shoplifting Women   P 
19 Other Theft Acts Men   N 
20  Shoplifting Women   N 
+0

這裏的表格有兩個條目,不是? – JohnK 2014-11-04 22:10:28