问题 使用purrr的rowwise()do()的等价物,现在不推荐使用by_row()?


既然purrr中的by_row()将被弃用,那么新的首选tidyverse实现是什么:

somedata = expand.grid(a=1:3,b=3,c=runif(3))
somedata %>%
  rowwise() %>% do(binom.test(x=.$a,n=.$b,p=.$c) %>% tidy())

看起来好像你可能将每一行嵌套到一个列中,然后使用map(),但我不确定如何进行嵌套操作......再加上它看起来有点模糊不清。有没有更好的办法?


8107
2018-06-28 07:04


起源

我有一个10万行的tibble。 Rowwise非常慢。任何想法如何做更有效的操作? - jzadra


答案:


这是一种方式 map

library(tidyverse)
library(broom)
do.call(Map, c(f = binom.test, unname(somedata))) %>%
      map_df(tidy)
#  estimate statistic    p.value parameter    conf.low conf.high              method alternative
#1 0.3333333         1 1.00000000         3 0.008403759 0.9057007 Exact binomial test   two.sided
#2 0.6666667         2 0.25392200         3 0.094299324 0.9915962 Exact binomial test   two.sided
#3 1.0000000         3 0.03571472         3 0.292401774 1.0000000 Exact binomial test   two.sided
#4 0.3333333         1 0.14190440         3 0.008403759 0.9057007 Exact binomial test   two.sided
#5 0.6666667         2 0.55583967         3 0.094299324 0.9915962 Exact binomial test   two.sided
#6 1.0000000         3 1.00000000         3 0.292401774 1.0000000 Exact binomial test   two.sided
#7 0.3333333         1 0.58810045         3 0.008403759 0.9057007 Exact binomial test   two.sided
#8 0.6666667         2 1.00000000         3 0.094299324 0.9915962 Exact binomial test   two.sided
#9 1.0000000         3 0.25948735         3 0.292401774 1.0000000 Exact binomial test   two.sided

或者只有 tidyverse 功能

somedata %>%
     unname %>%
     pmap(binom.test) %>% 
     map_df(tidy)
#estimate statistic    p.value parameter    conf.low conf.high              method alternative
#1 0.3333333         1 1.00000000         3 0.008403759 0.9057007 Exact binomial test   two.sided
#2 0.6666667         2 0.25392200         3 0.094299324 0.9915962 Exact binomial test   two.sided
#3 1.0000000         3 0.03571472         3 0.292401774 1.0000000 Exact binomial test   two.sided
#4 0.3333333         1 0.14190440         3 0.008403759 0.9057007 Exact binomial test   two.sided
#5 0.6666667         2 0.55583967         3 0.094299324 0.9915962 Exact binomial test   two.sided
#6 1.0000000         3 1.00000000         3 0.292401774 1.0000000 Exact binomial test   two.sided
#7 0.3333333         1 0.58810045         3 0.008403759 0.9057007 Exact binomial test   two.sided
#8 0.6666667         2 1.00000000         3 0.094299324 0.9915962 Exact binomial test   two.sided
#9 1.0000000         3 0.25948735         3 0.292401774 1.0000000 Exact binomial test   two.sided

10
2018-06-28 07:50



pmap中的函数调用是否允许您传递参数?例如,如果你希望binom.test中的“p”参数为“c-0.5”,我想做一些像pmap(binom.test(p = .z-0.5))的东西,但这显然没有不行。有同等的吗? - Nicholas Root
@NicholasRoot我想你需要 pmap(~binom.test(., p = z -0.5)) - akrun
请注意,你可以避免 unname 如果您使用列名称 somedata 匹配函数的参数(binom.test 在这种情况下)。这将更明确,因此可能更安全。 - cboettig