【发布时间】:2011-08-10 04:56:17
【问题描述】:
我正在尝试使用 plyr 包中的 daply 函数,但无法正确输出。尽管构成矩阵的变量是数字,但矩阵的元素是列表,而不是变量本身。例如,这里是数据的一小部分:
Month Vehicle Samples
1 Oct-10 31057 256
2 Oct-10 31059 316
3 Oct-10 31060 348
4 Nov-10 31057 267
5 Nov-10 31059 293
6 Nov-10 31060 250
7 Dec-10 31057 159
8 Dec-10 31059 268
9 Dec-10 31060 206
我希望能够以矩阵格式可视化数据,看起来像这样:
Month
Vehicle Oct-10 Nov-10 Dec-10
31057 256 267 159
31059 316 293 268
31060 348 250 206
这是我使用的几种替代语法(后者是因为我的原始数据框的列比我在此处显示的要多):
daply(DF, .(Vehicle, Month), identity)
daply(DF,.(Vehicle,Month), colwise(identity,.(Samples)))
然而我得到的却是相当深奥:
Month
Vehicle Oct-10 Nov-10 Dec-10
31057 List,3 List,3 List,3
31059 List,3 List,3 List,3
31060 List,3 List,3 List,3
正如一些评论者所建议的,我在输出中使用了str 函数,下面是摘录:
List of 9
$ :'data.frame': 1 obs. of 3 variables:
..$ Month : Ord.factor w/ 3 levels "Oct-10"<"Nov-10"<..: 1
..$ Vehicle: Factor w/ 3 levels "31057","31059",..: 1
..$ Samples: int 256
$ :'data.frame': 1 obs. of 3 variables:
..$ Month : Ord.factor w/ 3 levels "Oct-10"<"Nov-10"<..: 1
..$ Vehicle: Factor w/ 3 levels "31057","31059",..: 2
..$ Samples: int 316
我错过了什么?另外,有没有办法简单地使用基本包来做到这一点?谢谢!
下面是数据框的Dput,如果您想重现此内容:
structure(list(Month = structure(c(1L, 1L, 1L, 2L, 2L, 2L, 3L,
3L, 3L), .Label = c("Oct-10", "Nov-10", "Dec-10"), class = c("ordered",
"factor")), Vehicle = structure(c(1L, 2L, 3L, 1L, 2L, 3L, 1L,
2L, 3L), .Label = c("31057", "31059", "31060"), class = "factor"),
Samples = c(256L, 316L, 348L, 267L, 293L, 250L, 159L, 268L,
206L)), .Names = c("Month", "Vehicle", "Samples"), class = "data.frame", row.names = c(NA,
9L))
【问题讨论】:
-
更多信息会很有用。尝试 str(DF) 并将输出粘贴到问题中。或者使用 dput(DF) 为人们提供你的数据,如果它不是很大的话(如果它是子集的话)。
-
您在这里尝试做什么并不明显。您似乎正在尝试对数据进行某种形式的重塑,因为
identity不会对其参数执行任何操作。请告诉我们您的预期结果。 -
请参阅stackoverflow.com/questions/5963269/…,了解如何使您的问题中的代码可重现。
-
感谢您的编辑;这个问题现在好多了!这确实被称为重塑数据;使用该术语(和 R 标签)进行搜索会给出一些对您有帮助的结果:stackoverflow.com/search?q=%5Br%5D+reshape 我还在下面回答了您的问题,具体说明了为什么
identity不起作用。 -
stackoverflow.com/a/9617424/210673 现在列出了执行此操作的各种方法。