创建具有变量列表的单个变量的比例表

问题描述 投票:0回答:1

这可能是一个非常简单的问题,但我似乎无法弄清楚。

我创建了两个变量的比例表:

mtcars %>%
  group_by(cyl, carb)%>%
  summarise(n=n())%>%
  mutate(prop=n/sum(n))%>%
  subset(select=c("cyl", "carb", "prop"))%>%
  spread(cyl, prop)%>%
  kable()

现在,我想用cyl作为一个变量创建多个表,并循环遍历第二个变量的多个变量列表。这是我尝试过的一种无效的方法:

cols = c('vs', 'am', 'gear', 'carb')
for (q in cols) {
  map2(~prop.table(table(mtcars[[q]], mtcars[["cyl"]])))
}

提前感谢您的帮助!

r tidyverse
1个回答
0
投票

[这里,我们可以使用map循环遍历'cols',而不是for + map2返回输出的list

library(purrr)
lst1 <-  map(cols, ~ prop.table(table(mtcars[[.x]], mtcars[["cyl"]])))
lst1
#[[1]]

#          4       6       8
#  0 0.03125 0.09375 0.43750
#  1 0.31250 0.12500 0.00000

#[[2]]

#          4       6       8
#  0 0.09375 0.12500 0.37500
#  1 0.25000 0.09375 0.06250

#[[3]]

#          4       6       8
#  3 0.03125 0.06250 0.37500
#  4 0.25000 0.12500 0.00000
#  5 0.06250 0.03125 0.06250

#[[4]]

#          4       6       8
#  1 0.15625 0.06250 0.00000
#  2 0.18750 0.00000 0.12500
#  3 0.00000 0.00000 0.09375
#  4 0.00000 0.12500 0.18750
#  6 0.00000 0.03125 0.00000
#  8 0.00000 0.00000 0.03125

如果我们想使用tidyverse功能

library(dplyr)
library(tidyr)
map(cols, ~ mtcars %>%
               group_by_at(vars(cyl, .x)) %>%
               summarise(n = n()) %>%
               mutate(prop = n/sum(n)) %>% 
               select(cyl, !!.x, prop) %>%
               pivot_wider(names_from = cyl, values_from = prop))
© www.soinside.com 2019 - 2024. All rights reserved.