bfoste01
bfoste01

Reputation: 359

Creating a nested table with ddply

I'm having trouble generating a table with plyr and I hope you can help. If you run the code below you should get a table with proportions at the highest aggregate level of my data (i.e., the whole data set). However, I'd like to get the same table with proportions per item for each school. Thanks for any help. Also, if there's a better way to synthesize this with just dplyr I'm open to it. I'm trying to integrate some of these new packages into my workflow.

# load packages
library(plyr)
library(dplyr)
library(reshape2)
library(tidyr)
library(xtable)
# generate fake Data
set.seed(500)
School <- rep(seq(1:20), 2)
District <- rep(c(rep("East", 10), rep("West", 10)), 2)
Score <- rnorm(40, 100, 15)
Student.ID <- sample(1:1000,8,replace=T)
items <- data.frame(replicate(10, sample(1:4, 40, replace=TRUE)))
items <- data.frame(lapply(items, factor, ordered=TRUE, 
levels=1:4, 
labels=c("Strongly disagree","Disagree",
"Agree","Strongly Agree")))
school.data <- data.frame(Student.ID, School, District, Score, items)
rm(items)
# code for table
items <- select(school.data, School, X1:X10) 
g <- items %>% 
    gather(Item, response, -School)
# This gives me the aggregate results for the entire data set
foo <- ddply(g, .(Item), function(x)  prop.table(table(x$response))) #I stupidly tried .(Item, School) to no avail
xtable(foo)

Upvotes: 1

Views: 231

Answers (1)

lukeA
lukeA

Reputation: 54247

Try

prop.table(with(g, table(response, Item, School)), margin = 2) 

This gives a 4x10x20 array (responses, items, schools). You can use as.data.fame on the result for conversion if needed.

Upvotes: 1

Related Questions