当by_row()被弃用后,如何使用purrr中的rowwise() do()函数?

14

现在purrr中的by_row()将被(是吗?)弃用,那么什么是新的首选tidyverse实现呢?

Now that by_row() in purrr is going to be (is?) deprecated, what is the new preferred tidyverse implementation of:
somedata = expand.grid(a=1:3,b=3,c=runif(3))
somedata %>%
  rowwise() %>% do(binom.test(x=.$a,n=.$b,p=.$c) %>% tidy())

看起来你可以将每一行嵌套到单独的列中,然后使用 map(),但我不确定如何进行这种嵌套操作...而且这似乎有点晦涩。有更好的方法吗?


我有一个包含10万行的tibble。逐行处理非常缓慢。有什么更有效的操作方法吗? - jzadra
1个回答

13

这是使用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

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
2
请注意,如果您在somedata中使用与函数参数(在此情况下为binom.test)匹配的列名,则可以避免使用unname。这将更加明确,因此可能更安全。 - cboettig

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接