【发布时间】:2019-06-13 10:20:38
【问题描述】:
我正在探索 tidyverse 包。所以我对如何以整洁的方式完成以下任务感兴趣。使用*apply 函数可以轻松绕过该问题。
考虑以下数据
tb <-
lapply(matrix(c("a", "b", "c")), function(x)
rep(x, 3)) %>% unlist %>% c(rep(c(1, 2, 3), 6)) %>% matrix(ncol = 3) %>%
as_tibble(.name_repair = ~ c("tag", "x1", "x2")) %>% type.convert()
# A tibble: 9 x 3
tag x1 x2
<fct> <int> <int>
1 a 1 1
2 a 2 2
3 a 3 3
4 b 1 1
5 b 2 2
6 b 3 3
7 c 1 1
8 c 2 2
9 c 3 3
我使用 nest() 函数对它们进行分组,对于每个组,我想从函数列表中应用不同的函数 f_1, f_2, f_3
f_1 <- function(x)
x[,1] + x[,2]
f_2 <- function(x)
x[,1] - x[,2]
f_3 <- function(x)
x[,1] * x[,2]
tb_func_attached <-
tb %>% group_by(tag) %>% nest() %>% mutate(func = c(f_0, f_1, f_2))
# A tibble: 3 x 3
tag data func
<fct> <list> <list>
1 a <tibble [3 x 2]> <fn>
2 b <tibble [3 x 2]> <fn>
3 c <tibble [3 x 2]> <fn>
我尝试使用 invoke_map 来应用函数
tb_func_attached %>% {invoke_map(.$func, .$data)}
invoke_map(tb_func_attached$func, tb_func_attached$data)
但我得到错误Error in (function (x) : unused arguments (x1 = 1:3, x2 = 1:3),而下面的代码运行
> tb_func_attached$func[[1]](tb_func_attached$data[[1]])
x1
1 2
2 4
3 6
> tb_func_attached$func[[2]](tb_func_attached$data[[2]])
x1
1 0
2 0
3 0
> tb_func_attached$func[[3]](tb_func_attached$data[[3]])
x1
1 1
2 4
3 9
但是invoke_map还是不行。
所以问题是,给定一个嵌套数据tb_func_attached,如何将函数tb_func_attached$func 'rowwisely' 应用到tb_func_attached$data?
还有一个附带问题,invoke_map 退休的原因是什么?它非常适合 vetorisation 的概念,恕我直言。
更新:
以前的版本处理单列数据(tb 只有标签和x1 列)和@A。 Suliman 的评论提供了一个解决方案。
但是当嵌套tibble中的数据列有矩阵结构时,代码又停止运行了。
【问题讨论】:
-
将
val列重命名为x。 -
@A.Suliman 就这么简单?背后的原因是什么?
-
我认为列名应该与函数变量名匹配,例如考虑
?purrr::invoke_map;df <- tibble::tibble( f = c("runif", "rpois", "rnorm"), params = list( list(n = 10), list(n = 5, lambda = 10), list(n = 10, mean = -3, sd = 10) ) ) df invoke_map(df$f, df$params)、params使用每个函数的参数作为列表中的名称。 -
所以如果我想将它用于嵌套数据,我的函数应该始终将
data作为输入参数?