【发布时间】:2018-07-27 22:49:40
【问题描述】:
我正在尝试在嵌套 tibble 上为非标准类使用 map,特别是 lubridate 的 interval() 结果。我似乎无法在正确的班级中将其发送给unnest():
require(tidyverse)
#> Loading required package: tidyverse
#> Warning: package 'ggplot2' was built under R version 3.4.4
require(lubridate)
#> Loading required package: lubridate
#>
#> Attaching package: 'lubridate'
#> The following object is masked from 'package:base':
#>
#> date
df <- structure(list(date = structure(c(16073, 16073, 16210, 16286,
16486, 16498, 16518, 16539, 16618, 16426, 16496, 16588, 16602,
16602, 16629, 16654, 16714, 16769, 16776, 17379), class = "Date"),
id = c(8843, 8843, 8843, 8843, 8843, 8843, 8843, 8843, 8843,
8843, 8843, 8843, 8843, 8843, 8843, 8843, 8843, 8843, 8843,
8843)), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA,
-20L), .Names = c("date", "id"))
df %>%
group_by(id) %>%
nest() %>%
mutate(date_range = map(data, ~interval(min(.x$date), max(.x$date)))) %>%
unnest(date_range)
#> Warning in combine_all(args[[1]]): Vectorizing 'Interval' elements may not
#> preserve their attributes
#> # A tibble: 1 x 3
#> id data date_range
#> <dbl> <list> <dbl>
#> 1 8843 <tibble [20 × 1]> 112838400
由reprex package (v0.2.0) 于 2018 年 7 月 27 日创建。
有什么方法可以将 map 与非标准类一起使用,还是仍然不支持?
编辑(更新):
这会产生我想要的东西,但是这样做的效率很低。即使我有解决方法,我也希望学习如何正确执行此操作:
df %>%
group_by(id) %>%
nest() %>%
mutate(date_min = map(data, ~min(.x$date)),
date_max = map(data, ~max(.x$date))) %>%
unnest(date_min, date_max) %>%
mutate(date_range = interval(date_min, date_max))
【问题讨论】:
-
我认为
map正在做你所期望的,返回Interval对象的列表,但是unnest()将这些间隔强制为数字。?unnest表示它将在可以是原子向量、列表或数据帧的列表列上工作,但没有说任何关于工作S4 objects像Intervals 的内容,因此是连贯的(我猜)