![](/img/trans.png)
[英]Apply custom function that returns multiple values after dplyr::rowwise()
[英]How to use dplyr's rowwise() in pipe in R to apply a function that returns a list to each row?
我想使用dplyr的rowwise()和管道将函数(返回列表)应用于数据帧中的每一行。
测试数据集有两行:
test_tbl <- tibble(a=c(2, 4), b=c(0, 8), c=c(5, -3))
定义一个简单的函数(这是一个返回列表的函数,显然与添加8无关):
simple_function <- function(input) {
list(input + 8)
}
这是我要实现的目标:
apply(test_tbl ,1, function (x) simple_function(x))
它返回2个列表的列表(我想要的输出)。
我想将这些列表另存为小标题中的一列。 我们可以做:
test_tbl %>% mutate(output = apply(. ,1, function (x) simple_function(x)))
我宁愿使用dplyr而不是将dplyr,base和管道混合在一起(也是为了代码的可读性),但是我不明白为什么这不起作用:
test_tbl %>% rowwise() %>% simple_function
test_tbl %>% rowwise() %>% mutate(output = simple_function(.))
这两个函数都将函数应用于整个数据帧,而不是单独的行。 它是没有意义,我认为: test_tbl %>% rowwise() %>% simple_function
是相同的(在输出计)至test_tbl %>% simple_function
这确实提供了所需的输出,但是我发现它太冗长而不理想,我必须自己绑定列:
test_tbl %>% rowwise() %>% do(output= simple_function(.)) %>% bind_cols(test_tbl, .)
非常感谢对rowwise()
失败的任何帮助。
如果我们需要在每一行上执行此操作,请在map
split
并应用该函数
library(tidyverse)
test_tbl %>%
split(., seq_len(nrow(.))) %>%
map(simple_function)
#$`1`
#$`1`[[1]]
# a b c
#1 10 8 13
#$`2`
#$`2`[[1]]
# a b c
#1 12 16 5
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.