我想使用dplyr的rowwise()和管道对dataframe中的每一行应用一个函数(返回一个列表)。
包含两行的测试数据集:
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()失败原因的帮助都是非常感谢的。
发布于 2017-09-25 18:14:21
如果我们需要对每一行执行此操作,则在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 5https://stackoverflow.com/questions/46402462
复制相似问题