我需要制作一百万张表,所以我不是在循环,而是在尝试使我的代码功能化。但是,我无法使功能正常工作,我也不知道为什么。以下是一些可以使用的示例数据:
# example data:
set.seed(1)
dframe <- data.frame(time=c(rep("before", 6), rep("after", 4)),
Quest1=sample(0:5, 10, replace=TRUE))
dframe
# result:
time Quest1
1 before 1
2 before 2
3 before 3
4 before 5
5 before 1
6 before 5
7 after 5
8 after 3
9 after 3
10 after 0
这是我尝试过的代码:
# works:
tab1 <- prop.table(with(dframe, table(time, factor(Quest1, c(0:5)))), 1)
tab1
# result:
time 0 1 2 3 4 5
after 0.250 0.000 0.000 0.500 0.000 0.250
before 0.000 0.333 0.167 0.167 0.000 0.333
# doesn't work:
makeTab = function(data, rowVar, colVar) {
prop.table(with(data, table(rowVar, factor(colVar, c(0:5)))), 1)
}
tab1 <- makeTab(dframe, time, Quest1)
# result:
Error in factor(colVar, c(0:5)) : object 'Quest1' not found
# works:
tab1 <- prop.table(table(dframe$time, factor(dframe$Quest1, c(0:5))), 1)
tab1
# (result same as above)
# doesn't work:
makeTab = function(data, rowVar, colVar) {
prop.table(table(data$rowVar, factor(data$colVar, c(0:5))), 1)
}
tab1 <- makeTab(dframe, time, Quest1)
tab1
# result:
0 1 2 3 4 5
请注意,循环确实有效:
# works:
tab <- list()
for(i in 1:1){
tab[[i]] <- prop.table(table(dframe$time, factor(dframe[,i+1], c(0:5))), 1)
}
tab
# result:
[[1]]
0 1 2 3 4 5
after 0.250 0.000 0.000 0.500 0.000 0.250
before 0.000 0.333 0.167 0.167 0.000 0.333