gpt4 book ai didi

r - 如何在列表列上应用一个函数并在 dplyr 和 purrr 中返回另一个函数?

转载 作者:行者123 更新时间:2023-12-05 09:19:36 24 4
gpt4 key购买 nike

我想获取列表列中每个向量中的前 5 个值,并将其作为保存为列表的数据框中的新列返回。

structure(list(sample_num = 1:6, vector = list(c(0, 1, 1, 0, 
1, 2, 0, 0, 3, 0), c(0, 0, 1, 2, 0, 0, 4, 10, 12, 1), c(1, 33,
4, 4, 2, 2, 6, 9, 14, 2), c(0, 0, 1, 0, 1, 0, 1, 5, 3, 0), c(0,
1, 1, 0, 0, 0, 1, 4, 3, 0), c(0, 0, 1, 0, 0, 0, 1, 1, 1, 0))), class = c("tbl_df",
"tbl", "data.frame"), row.names = c(NA, -6L), .Names = c("sample_num",
"vector"))

> test
# A tibble: 6 × 2
sample_num vector
<int> <list>
1 1 <dbl [10]>
2 2 <dbl [10]>
3 3 <dbl [10]>
4 4 <dbl [10]>
5 5 <dbl [10]>
6 6 <dbl [10]>

我尝试使用 lmap 但我收到错误消息

> test  %>% lmap(.$vector,.f = function(x) x[1:5])
Error in .f(.x[i], ...) :
unused argument (list(c(0, 1, 1, 0, 1, 2, 0, 0, 3, 0), c(0, 0, 1, 2, 0, 0, 4, 10, 12, 1), c(1, 33, 4, 4, 2, 2, 6, 9, 14, 2), c(0, 0, 1, 0, 1, 0, 1, 5, 3, 0), c(0, 1, 1, 0, 0, 0, 1, 4, 3, 0), c(0, 0, 1, 0, 0, 0, 1, 1, 1, 0)))

谢谢!

最佳答案

这是你想要做的吗?

structure(list(sample_num = 1:6, vector = list(c(0, 1, 1, 0, 
1, 2, 0, 0, 3, 0), c(0, 0, 1, 2, 0, 0, 4, 10, 12, 1), c(1, 33,
4, 4, 2, 2, 6, 9, 14, 2), c(0, 0, 1, 0, 1, 0, 1, 5, 3, 0), c(0,
1, 1, 0, 0, 0, 1, 4, 3, 0), c(0, 0, 1, 0, 0, 0, 1, 1, 1, 0))), class = c("tbl_df",
"tbl", "data.frame"), row.names = c(NA, -6L), .Names = c("sample_num",
"vector"))

test$new = lapply(test$vector, function(x) {x[1:5]})
test

# A tibble: 6 × 3
sample_num vector new
<int> <list> <list>
1 1 <dbl [10]> <dbl [5]>
2 2 <dbl [10]> <dbl [5]>
3 3 <dbl [10]> <dbl [5]>
4 4 <dbl [10]> <dbl [5]>
5 5 <dbl [10]> <dbl [5]>
6 6 <dbl [10]> <dbl [5]>


test$vector[3]
[[1]]
[1] 1 33 4 4 2 2 6 9 14 2

test$new[3]
[[1]]
[1] 1 33 4 4 2

如果要使用dplyr语法,先定义一个函数:

f = function(x) {
return(list(x[1:5]))
}

然后,将它逐行应用到列 vector

test = test %>%
rowwise() %>%
mutate(new_dplyr = f(vector))

test
# A tibble: 6 × 3
sample_num vector new_dplyr
<int> <list> <list>
1 1 <dbl [10]> <dbl [5]>
2 2 <dbl [10]> <dbl [5]>
3 3 <dbl [10]> <dbl [5]>
4 4 <dbl [10]> <dbl [5]>
5 5 <dbl [10]> <dbl [5]>
6 6 <dbl [10]> <dbl [5]>

test$vector[3]
[[1]]
[1] 1 33 4 4 2 2 6 9 14 2

test$new_dplyr[3]
[[1]]
[1] 1 33 4 4 2

关于r - 如何在列表列上应用一个函数并在 dplyr 和 purrr 中返回另一个函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40138595/

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