我正在寻找一种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)
映射单个函数,但是我想在列表中添加新元素并在一个管道中完成。
答案 0 :(得分:2)
l <- list(c("a", "a", "b"), c("c", "d"), c("e", "f", "e", "g"))
Purr
方法:
l %>%
map(~ list(vec = .,
length = length(.),
unique = length(unique(.))))
输出
[[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 %>%
tibble(vec = .) %>%
mutate(length = map_dbl(vec, length),
unique = map_dbl(vec, ~length(unique(.))))
输出:
# A tibble: 3 x 3
vec length unique
<list> <dbl> <dbl>
1 <chr [3]> 3 2
2 <chr [2]> 2 2
3 <chr [4]> 4 3