R 数据帧到4D阵列
我需要将数据帧(R 数据帧到4D阵列,r,arrays,R,Arrays,我需要将数据帧(“d”在下面的虚拟代码中)重塑为4D数组。在特定情况下,我希望下面的变量“count”包含在一个4D数组中,该数组的维度为site by year by date by method 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),
“d”
在下面的虚拟代码中)重塑为4D数组。在特定情况下,我希望下面的变量“count”
包含在一个4D数组中,该数组的维度为site by year by date by method
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)))
d我们可以使用xtabs()
资料
d
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))