使用 dplyr 将函数应用于 data.frame 中的一行

Apply function to a row in a data.frame using dplyr

在基础 R 中,我将执行以下操作:

d <- data.frame(a = 1:4, b = 4:1, c = 2:5)
apply(d, 1, which.max)

使用 dplyr 我可以执行以下操作:

library(dplyr)
d %>% mutate(u = purrr::pmap_int(list(a, b, c), function(...) which.max(c(...))))

如果 d 中还有另一列,我需要指定它,但我希望它可以使用任意数量的列。

从概念上讲,我想要这样的东西

pmap_int(list(everything()), ...)
pmap_int(list(.), ...)

但这显然行不通。我如何用 dplyr 规范地解决这个问题?

我们只需要将数据指定为 .,因为 data.frame 是一个 list,其中列作为列表元素。如果我们换行list(.),它就变成了一个嵌套列表

library(dplyr)
d %>% 
  mutate(u = pmap_int(., ~ which.max(c(...))))
#  a b c u
#1 1 4 2 2
#2 2 3 3 2
#3 3 2 4 3
#4 4 1 5 3

或者可以使用cur_data()

d %>%
   mutate(u = pmap_int(cur_data(), ~ which.max(c(...))))

或者,如果我们想使用 everything(),请将其放在 select 中,因为 list(everything()) 不会处理应从中选择所有内容的数据

d %>% 
   mutate(u = pmap_int(select(., everything()), ~ which.max(c(...))))

或使用rowwise

d %>%
    rowwise %>% 
    mutate(u = which.max(cur_data())) %>%
    ungroup
# A tibble: 4 x 4
#      a     b     c     u
#  <int> <int> <int> <int>
#1     1     4     2     2
#2     2     3     3     2
#3     3     2     4     3
#4     4     1     5     3

或者 max.col

更有效
max.col(d, 'first')
#[1] 2 2 3 3

collapse

library(collapse)
dapply(d, which.max, MARGIN = 1)
#[1] 2 2 3 3

可以作为

包含在dplyr
d %>% 
    mutate(u = max.col(cur_data(), 'first'))

这里有一些 data.table 选项

setDT(d)[, u := which.max(unlist(.SD)), 1:nrow(d)]

setDT(d)[, u := max.col(.SD, "first")]