我的数据参差不齐,在不同城市的不同学校里有不同的班级。
city <- c(1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3)
school <- c(1,1,1,1,1,1,2,2,2,3,3,3,4,4,4,4,5,5,5,6,6,7,7,7,7,7,
8,8,8,8,9,9,9,9,9,9,10,10,10,10,10,10,10)
x1 <- c(23,43,12,23,34,43,23,23,12,23,34,17,36,26,25,28,33,33,33,13,25,25,
35,34,23,19,18,27,33,28,23,23,12,23,34,17,36,23,34,17,36,26,25)
x2 <- c(33,13,25,25,35,34,23,19,18,27,23,43,12,23,34,43,23,23,12,23,33,33,
28,23,23,12,23,34,17,36,23,34,17,36,26,25,34,17,36,26,25,28,33)
x3 <- c(22,18,25,23,22,33,23,22,18,22,28,38,26,18,19,28,27,23,26,24,37,28,
28,22,24,17,24,32,16,38,25,33,19,31,25,24,32,18,33,23,22,25,36)
data<- data.frame(city,school,x1,x2,x3)
我想创建3路数据结构并使用for循环访问每个类的值(x1-x3)?
(注意:由于我无法与[[]]
一起使用,因此我不在列表r-jags
中寻找列表。
如何指定不同的班级和学校?一个建议是使用每所学校内每个班级的最大人数!
for (i in length(unique(city))) { # number of cities
for (j in ... ) { # number of school in each city
for (k in ... ) # number of classes in each school
y[k,j,i] <- mean + beta1*x1[k,j,i] + beta2*x2[k,j,i]
}
}
注意,我提供的数据是海量数据的子集。我想使用for循环来提取每个单个值(例如x1 [1,1,1] = 23)。 另外,有没有办法为学校和班级指定所有不同的维度?
答案 0 :(得分:0)
这可能会做您想要的。数据数据帧可以转换为3维数组。
X <- array(NA, dim=c(3, 10, 3), dimnames=list(city=1:3, school=1:10,
classes=c("X1", "X2", "X3")))
X[,,1] <- xtabs(x1~city + school, data)
X[,,2] <- xtabs(x2~city + school, data)
X[,,3] <- xtabs(x3~city + school, data)
str(X)
# num [1:3, 1:10, 1:3] 178 0 0 58 0 0 74 0 0 0 ...
# - attr(*, "dimnames")=List of 3
# ..$ city : chr [1:3] "1" "2" "3"
# ..$ school : chr [1:10] "1" "2" "3" "4" ...
# ..$ classes: chr [1:3] "X1" "X2" "X3"
ftable(X, row.vars=c(1, 3), col.vars=2)
# school 1 2 3 4 5 6 7 8 9 10
# city classes
# 1 X1 178 58 74 0 0 0 0 0 0 0
# X2 165 60 93 0 0 0 0 0 0 0
# X3 143 63 88 0 0 0 0 0 0 0
# 2 X1 0 0 0 115 99 38 136 106 0 0
# X2 0 0 0 112 58 56 119 110 0 0
# X3 0 0 0 91 76 61 119 110 0 0
# 3 X1 0 0 0 0 0 0 0 0 132 197
# X2 0 0 0 0 0 0 0 0 161 199
# X3 0 0 0 0 0 0 0 0 157 189