使用Purrr :: Invoke()与Table和Chisq.Test来改进工作流程

时间:2017-03-18 04:53:20

标签: r tidyverse purrr

library(purrr)
library(tidyverse)

我试图更好地理解purrr::invoke()功能。我觉得我想要的东西很简单,这对我的工作流程有帮助。我承认我对" do.call"没有理解,为此" invoke"是一个包装。

例如,我使用" happy"来自ggmosaic包的数据集,但任何具有各种因子列的数据集都可以使用。

我试图使用" invoke"在选定的因子列上运行一些表,但没有成功。我只想根据因子列名列表生成一些简单的表。

像这样......

happy%>%invoke(table,list(c("health",c("happy"))

happy%>%select_if(is.factor)%>%invoke(table)

L <- list("health","happy","degree")
happy%>%invoke(table,L)

我也很想知道如何以其他方式将purrr::invoke()合并到我的工作流程中,例如chisq.test

1 个答案:

答案 0 :(得分:0)

如果您希望在数据框的行上迭代函数,建议您考虑transpose + map而不是invoke

library(ggmosaic) 
library(purrr)
library(tidyverse) 

data(happy)

h <- 
  happy %>% 
  as_tibble %>% 
  sample_n(100)  ## use a subset for the example

h %>% 
  select_if(is.factor) %>% 
  transpose() %>% 
  map(table) %>% 
  mutate(h, TABLE = .) %>%  
  select(TABLE, everything())
#> # A tibble: 100 × 11
#>          TABLE    id         happy  year   age    sex       marital
#>         <list> <dbl>        <fctr> <dbl> <dbl> <fctr>        <fctr>
#> 1  <S3: table>   417    very happy  1975    68 female       married
#> 2  <S3: table>   529  pretty happy  1983    20 female       married
#> 3  <S3: table>   226  pretty happy  1973    32 female       married
#> 4  <S3: table>  1327 not too happy  1974    39   male       married
#> 5  <S3: table>  1632  pretty happy  1976    40   male      divorced
#> 6  <S3: table>    46 not too happy  1982    31 female       married
#> 7  <S3: table>   729  pretty happy  1994    85 female       widowed
#> 8  <S3: table>   557  pretty happy  1985    47 female      divorced
#> 9  <S3: table>   136  pretty happy  1978    48 female       married
#> 10 <S3: table>  1020    very happy  2000    21   male never married
#> # ... with 90 more rows, and 4 more variables: degree <fctr>,
#> #   finrela <fctr>, health <fctr>, wtssall <dbl>

但是这个结果似乎不是很有用 - 或许你可以map对剪裁后的数据集进行总结?

h %>% select_if(is.factor) %>% map(table)
#> $happy
#> 
#> not too happy  pretty happy    very happy 
#>             9            50            30 
#> 
#> $sex
#> 
#>   male female 
#>     53     47 
#> 
#> $marital
#> 
#>       married never married      divorced       widowed     separated 
#>            53            25            14             7             0 
#> 
#> $degree
#> 
#> lt high school    high school junior college       bachelor       graduate 
#>             25             44              6             16              8 
#> 
#> $finrela
#> 
#> far below average     below average           average     above average 
#>                 6                25                41                16 
#> far above average 
#>                 0 
#> 
#> $health
#> 
#>      poor      fair      good excellent 
#>         4        13        41        18