使用 Tidyverse 方法将数据集拆分为多个表
Splitting a Dataset into Multiple Tables Using Tidyverse Methods
library(ggmosaic)
library(tidyverse)
我正在努力使用 Tidyverse 方法将数据集拆分为多个 table。我将使用下面的代码创建一个结构与我的实际数据有些相似的数据集。
happy2<-happy%>%
select(sex,marital,degree,health)%>%
group_by(sex,marital,degree,health)%>%
summarise(Count=n())
现在,使用 happy2 数据集,我想按 "degree" 拆分数据,在每个学位类别中,将有两个 table,一个男性,一个男性女性,基于 "sex" 变量。每个 table 都有 "marital" 和 "Count" 作为列,"health" 作为行。
我希望找到一种使用 Tidyverse 方法(例如 tidyr::nest、purrr 或 split)创建这些 table 的优雅方法。
这似乎是 split 的一个相当直接的应用:
# For a flat list
happy2 %>%
split(list(.$degree, .$sex))
# For a nested list
happy2 %>%
split(.$degree) %>%
lapply(function(x) split(x, x$sex))
两种方法都很有效,语法也相当简洁易懂;我不确定为什么 tidyverse 等价物应该是可取的。
library(ggmosaic)
library(tidyverse)
我正在努力使用 Tidyverse 方法将数据集拆分为多个 table。我将使用下面的代码创建一个结构与我的实际数据有些相似的数据集。
happy2<-happy%>%
select(sex,marital,degree,health)%>%
group_by(sex,marital,degree,health)%>%
summarise(Count=n())
现在,使用 happy2 数据集,我想按 "degree" 拆分数据,在每个学位类别中,将有两个 table,一个男性,一个男性女性,基于 "sex" 变量。每个 table 都有 "marital" 和 "Count" 作为列,"health" 作为行。
我希望找到一种使用 Tidyverse 方法(例如 tidyr::nest、purrr 或 split)创建这些 table 的优雅方法。
这似乎是 split 的一个相当直接的应用:
# For a flat list
happy2 %>%
split(list(.$degree, .$sex))
# For a nested list
happy2 %>%
split(.$degree) %>%
lapply(function(x) split(x, x$sex))
两种方法都很有效,语法也相当简洁易懂;我不确定为什么 tidyverse 等价物应该是可取的。