我需要将数据帧(下面的伪代码中的"d"
整形为4D数组。在特定情况下,我希望将下面的变量"count"
包含在4D数组中,并按方法逐年按日期定位维度。
d <- data.frame(site=c(rep("aaa", 4), rep("bbb", 4)), date=c(114:117, 220:223),
year=c(2005:2008, 2009:2012), count=rpois(8, 34),
method=c(rep(1, 2), rep(2, 2), rep(1, 1), rep(2, 3)))
答案 0 :(得分:0)
我们可以使用xtabs()
。
xtabs(count ~ ., d)
# , , year = 2005, method = 1
#
# date
# site 114 115 116 117 220 221 222 223
# aaa 45 0 0 0 0 0 0 0
# bbb 0 0 0 0 0 0 0 0
#
# , , year = 2006, method = 1
#
# date
# site 114 115 116 117 220 221 222 223
# aaa 0 38 0 0 0 0 0 0
# bbb 0 0 0 0 0 0 0 0
#
# [...]
# , , year = 2005, method = 2
#
# date
# site 114 115 116 117 220 221 222 223
# aaa 0 0 0 0 0 0 0 0
# bbb 0 0 0 0 0 0 0 0
#
# , , year = 2006, method = 2
#
# date
# site 114 115 116 117 220 221 222 223
# aaa 0 0 0 0 0 0 0 0
# bbb 0 0 0 0 0 0 0 0
#
# [...]
d <- structure(list(site = structure(c(1L, 1L, 1L, 1L, 2L, 2L, 2L,
2L), .Label = c("aaa", "bbb"), class = "factor"), date = c(114L,
115L, 116L, 117L, 220L, 221L, 222L, 223L), year = 2005:2012,
count = c(45L, 38L, 35L, 36L, 30L, 42L, 25L, 31L), method = c(1,
1, 2, 2, 1, 2, 2, 2)), class = "data.frame", row.names = c(NA,
-8L))