【发布时间】:2019-04-27 10:38:20
【问题描述】:
我正在寻找一种 tidyverse / purrr 向列表添加元素的方法。例如:
library(tidyverse)
l <- list(c("a", "a", "b"), c("c", "d"), c("e", "f", "e", "g"))
l
[[1]]
[1] "a" "a" "b"
[[2]]
[1] "c" "d"
[[3]]
[1] "e" "f" "e" "g"
如何构建管道%>% 以返回如下内容:
desired <- list(
list(vec = c("a", "a", "b"), length = 3, unique = 2),
list(vec = c("c", "d"), length = 2, unique = 2),
list(vec = c("e", "f", "e", "g"), length = 4, unique = 3)
)
desired
[[1]]
[[1]]$vec
[1] "a" "a" "b"
[[1]]$length
[1] 3
[[1]]$unique
[1] 2
[[2]]
[[2]]$vec
[1] "c" "d"
[[2]]$length
[1] 2
[[2]]$unique
[1] 2
[[3]]
[[3]]$vec
[1] "e" "f" "e" "g"
[[3]]$length
[1] 4
[[3]]$unique
[1] 3
我知道我可以使用 l %>% map(length) 或 l %>% map(unique) 映射单个函数,但我想向列表中添加新元素并在一个管道中执行此操作。
【问题讨论】: