我想使用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个列表的列表(我想要的输出) .
我想将这些列表保存为tibble中的列 . 我们可以这样做:
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()
失败的帮助都非常感谢 .
1 回答
如果我们需要在每一行上执行此操作,那么
split
并在map
中应用该函数