向列表中添加元素的tidyverse-purrr方法
我正在寻找一种将元素添加到列表中的向列表中添加元素的tidyverse-purrr方法,r,tidyverse,purrr,R,Tidyverse,Purrr,我正在寻找一种将元素添加到列表中的tidyverse/purr方法。例如: 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" 我知道我可以使用l%>%map(length)或l%>%map(unique)映射单个函数,但我想在列表中添
tidyverse
/purr
方法。例如:
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"
我知道我可以使用l%>%map(length)
或l%>%map(unique)
映射单个函数,但我想在列表中添加新元素,并在一个管道中完成此操作
l <- list(c("a", "a", "b"), c("c", "d"), c("e", "f", "e", "g"))
输出
[[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
但是,我会尽可能坚持使用数据帧(TIBLES):
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
#一个tible:3 x 3
vec长度唯一
1 3 2
2 2 2
3 4 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