使用 ddply 创建嵌套 table

Creating a nested table with ddply

我在使用 plyr 生成 table 时遇到问题,希望您能提供帮助。如果您 运行 下面的代码,您应该得到一个 table ,其比例处于我数据的最高聚合级别(即整个数据集)。但是,我希望每个学校的每个项目的比例相同 table。谢谢你的帮助。另外,如果有更好的方法可以仅用 dplyr 来合成它,我愿意接受。我正在尝试将其中一些新包集成到我的工作流程中。

# 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)

尝试

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

这给出了一个 4x10x20 数组(响应、项目、学校)。如果需要,您可以对结果使用 as.data.fame 进行转换。