1

我想使用 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()非常感谢任何有关失败原因的帮助。

4

1 回答 1

2

如果我们需要在每一行上执行此操作,然后在split其中应用函数map

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
于 2017-09-25T10:14:21.413 回答