Reputation: 101
Ok so I want to create a simple 2x2 table and then analyse this via a chi-square distribution
Variable A: 2 levels
Variable B: 2 levels
Easy enough. But I want to create 4 separate tables based on a third variable
Variable C: 4 levels
I know I can split the data into 4 separate data-files and do this but is there a simpler way to do this, and do so in a way that it creates 4 tables that I can then perform a chi-square analysis on?
Conservatives <- table(Data$Belief, Data$Group)[Data$Party=1]
Edit: Found the solution
with(Data,by(cbind(Belief,Group),list(factor(Party)),table))
with(Data,by(cbind(Belief,Group),list(factor(Party)),function(x){
chisq.test(table(x))
}))
H2 <- table(Data$Belief, Data$Group, Data$Party)
prop.table(H2, c(2,3))
Upvotes: 0
Views: 99
Reputation: 10385
Here is an example using mtcars data frame, the result is stored in a list
with(mtcars,by(cbind(mpg,cyl),list(factor(vs)),table))
Edit: storing the result is as simple as specifying a variable name in front. Same goes for the test, you can loop through the list and apply the test, or alternatively
with(mtcars,by(cbind(mpg,cyl),list(factor(vs)),function(x){
chisq.test(table(x))
}))
Upvotes: 1