[英]dplyr: apply function table() to each column of a 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
中还有另一列,我需要指定它,但我希望它可以在任意数量的 if 列中工作。
从概念上讲,我想要类似的东西
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")]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.