【发布时间】:2014-03-27 18:24:45
【问题描述】:
来自 data.frame 的示例:
x = data.frame(c(1,1,2,2,3,3), c(1,2,1,2,1,2), c(1,1,1,2,2,2), c(12,14,22,24,34,28))
colnames(x)=c("Store","Dept","Year","Sales")
我想获得:
Sales = array(NA, dim=c(2,2,2))
销售额是 3 个维度的数组:(商店、部门、年份)填充了来自 x 的所有数据。
我正在寻找一种可扩展到更多维度以及初始数据框 (x) 中的数千条记录的解决方案。
编辑:我认为下面的解决方案有效,但似乎它们并不是我想要的。我认为问题是索引在这个过程中丢失了。
这是一个小数据集:
structure(list(Store = c(35L, 35L, 35L, 35L, 35L), Dept = c(71L,
71L, 71L, 71L, 71L), Year = c(1, 2, 3, 4, 5), Sales = c(10908.04,
12279.99, 11061.82, 12288.1, 9950.55)), .Names = c("Store", "Dept",
"Year", "Sales"), row.names = c(NA, -5L), class = "data.frame")
> x
Store Dept Year Sales
1 35 71 1 10908.04
2 35 71 2 12279.99
3 35 71 3 11061.82
4 35 71 4 12288.10
5 35 71 5 9950.55
现在我希望能够致电 Sales[35,71,2] 以获取 10908.04。
以下两种解决方案都通过调用 Sales[1,1,1] 来获取数据,此时我无法使用。
【问题讨论】:
-
数组的
dimensions 应该是c(3, 2, 2)(三个Stores,两个Dept,两年)? -
@Henrik 是的,正确。
标签: r