我有一个数据表,其中包含许多产品的日期消耗。我生成了每个产品的预测,现在想要获得平均值,并在期间+1上限80%。问题是预测对象是一个具有不同结构的列表,具体取决于所使用的方法,因此我无法通过索引来检索值(我可以使用data.table
的名称来检索。)
这是(虚拟)数据和代码:
# load required libraries
library(data.table)
library(xts)
library(forecast)
library(dplyr)
# create random data
set.seed(1)
a <- data.table(prod = sample(LETTERS[1:5], 20, TRUE), cons = sample(1:50, 20, TRUE), dt = sample(seq(as.Date("2016/06/01"), as.Date("2016/07/27"), by = "day"), 20, FALSE))
# create a time series of purchases
b <- a[, .(C=sum(cons)), by = .(dt, prod)][, x := .(list(xts(x = C, order.by = dt))), by = prod]
b <- b[, .SD[1,], by = prod]
# create a "reference" timeseries
dts <- xts(order.by = seq(as.Date("2016/06/01"), as.Date("2016/07/27"), by = "day"))
# merge reference and calculated timeseries, so zeros appear
b[, x2 := .(list(merge.xts(dts, x[[1]], fill = 0))), by = prod]
# calculate forecast for each extended timeseries
b[, fc := .(list(forecast(x2[[1]]))), by = prod]
现在我想提取平均值和上限。问题是,平均有时位于列表的第2个插槽中,有时不在,所以我必须按名称调用它。在data.table
我做:
b[, mn := fc[[1]]$mean[1], by = prod]
b[, up := fc[[1]]$upper[1,1], by = prod]
但是如果我试图在dplyr
中做同样的事情,那么我会收到一个关闭错误:
b %>% mutate(mnD = .$fc[[1]]$mean[1])
## Error: invalid subscript type 'closure'
b %>% mutate(mnD = fc[[1]]$mean[1])
## Error: invalid subscript type 'closure'
我做错了什么,我怎样才能在dplyr
中实现这个目标?
答案 0 :(得分:5)
与map_dbl()
包中的purrr
结合使用将如下:
library(dplyr)
library(purrr)
b %>% as_data_frame() %>% mutate(mnD = map_dbl(fc, ~ .$mean[1]))
#> # A tibble: 5 x 7
#> prod dt C x x2 fc mnD
#> <chr> <date> <int> <list> <list> <list> <dbl>
#> 1 B 2016-07-17 47 <S3: xts> <S3: xts> <S3: forecast> 2.5241999
#> 2 C 2016-07-14 33 <S3: xts> <S3: xts> <S3: forecast> 1.1749266
#> 3 E 2016-06-30 7 <S3: xts> <S3: xts> <S3: forecast> 0.5952119
#> 4 D 2016-06-24 20 <S3: xts> <S3: xts> <S3: forecast> 3.3695962
#> 5 A 2016-07-04 18 <S3: xts> <S3: xts> <S3: forecast> 0.8421001
除此之外,不需要as_data_frame()
,但添加了以完整的方式打印结果。没有它,列表列将打印所有数据。