我使用janitory和lapply中的tabyl函数创建了一个嵌套的数据框列表。由于具有三个变量的tabyl函数返回数据帧列表,因此使用lapply会生成嵌套列表。在这种情况下,我正在研究民主表现和地区的不同变量。结果看起来像这样:
$ Freedom of Expression
..$ Africa (tabyl)
..$ Asia (tabyl)
..$ Europe (tabyl)
$ Freedom of Movement
..$ Africa (tabyl)
..$ Asia (tabyl)
..$ Europe (tabyl)
每个区域都有一个如下所示的数据框:
regime High Freedom of Expression Low Freedom of Expression Mid-Range Freedom of Expression Total
Democracy 100.0% (1) 0.0% (0) 70.0% (21) 44.9% (22)
Hybrid Regime 0.0% (0) 38.9%(7) 30.0% (9) 32.7% (16)
Non-Democratic Regime 0.0% (0) 61.1% (11) 0.0% (0) 22.4% (11)
我想将其导出为.csv或文本文件,以便与不知道如何使用R的人分享。
我尝试过使用purrr中的flatten函数,但这会产生一个区域列表,但只有一个变量的交叉表。我还使用了rlist包中的list.flatten,但它最终将数据帧的每一行作为列表中的单独元素返回。
感谢任何建议。
第一个map(bind_rows)
(深度1),然后是第二个bind_rows
library(tidyverse)
library(janitor)
#>
#> Attaching package: 'janitor'
#> The following objects are masked from 'package:stats':
#>
#> chisq.test, fisher.test
lapply(
replicate(2, mtcars, simplify = FALSE),
tabyl, cyl, gear, am
) %>%
map(bind_rows, .id = "region") %>%
bind_rows(.id = "freedom_of")
#> freedom_of region cyl 3 4 5
#> 1 0 4 1 2 0
#> 1 0 6 2 2 0
#> 1 0 8 12 0 0
#> 1 1 4 0 6 2
#> 1 1 6 0 2 1
#> 1 1 8 0 0 2
#> 2 0 4 1 2 0
#> 2 0 6 2 2 0
#> 2 0 8 12 0 0
#> 2 1 4 0 6 2
#> 2 1 6 0 2 1
#> 2 1 8 0 0 2
由reprex package创建于2019-04-30(v0.2.1)