gpt4 book ai didi

r - 将元素添加到列表的 tidyverse purrr 方法

转载 作者:行者123 更新时间:2023-12-04 01:50:17 24 4
gpt4 key购买 nike

我正在寻找一种 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) 映射单个函数,但我想添加新的列表中的元素,并在一个管道中执行此操作。

最佳答案

l <- list(c("a", "a", "b"), c("c", "d"), c("e", "f", "e", "g"))

咕噜咕噜方法:

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

但是我会尽可能坚持使用数据框(tibbles):

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

关于r - 将元素添加到列表的 tidyverse purrr 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53470018/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com