自动将输出分离到 R 中的多个对象中

separate output into multiple objects in R automatically

我不确定这是否可行,但是在 R 中有没有办法 运行 一个命令并让它根据组将输出保存到多个对象中?例如,我写了一个代码,根据部门计算有多少员工担任主管职务。

library(tidyverse)
sample <- tibble(department = c("Admin", "Admin", "Office of President", "Office of President"),
                 sup_status = c("Not Supervisor", "Supervisor", "Not Supervisor", "Supervisor"),
                 n = c(918, 152, 69, 192))

但是,我真正想要的是按部门划分的主管百分比向量。我可以让 R 生成一个包含所有百分比的长向量:

library(tidyverse)

vector_of_all_percents <- sample %>%
  group_by(department) %>%
  mutate(sum_new = sum(n)) %>%
  rowwise() %>%
  mutate(percent = n/sum_new) %>%
  select(percent) %>%
  as_vector()

vector_of_all_percents
 percent1  percent2  percent3  percent4 
0.8579439 0.1420561 0.2643678 0.7356322 

我的实际数据有很多部门。有没有办法调整我上面的代码,让 R 自动按部门生产对象,像这样:

vector_for_admin
 percent1  percent2
0.8579439 0.1420561 

vector_for_office
percent1  percent2 
0.2643678 0.7356322

我不确定 slice() 或 split() 命令是否是我需要的,或者这是否可能。任何指导将不胜感激!

您可以使用 split 创建列表:

library(tidyverse)
sample <- tibble(department =c("Admin", "Admin", "Office of President", "Office of President"),
                 sup_status =c("Not Supervisor", "Supervisor", "Not Supervisor", "Supervisor"),
                 n = c(918, 152, 69, 192))

list_of_all_percents <- sample %>%
  group_by(department) %>%
  mutate(sum_new = sum(n)) %>%
  rowwise() %>%
  mutate(percent = n/sum_new) %>%
  split(.$department)

list_of_all_percents
#> $Admin
#> Source: local data frame [2 x 5]
#> Groups: <by row>
#> 
#> # A tibble: 2 x 5
#>   department sup_status         n sum_new percent
#>   <chr>      <chr>          <dbl>   <dbl>   <dbl>
#> 1 Admin      Not Supervisor   918    1070   0.858
#> 2 Admin      Supervisor       152    1070   0.142
#> 
#> $`Office of President`
#> Source: local data frame [2 x 5]
#> Groups: <by row>
#> 
#> # A tibble: 2 x 5
#>   department          sup_status         n sum_new percent
#>   <chr>               <chr>          <dbl>   <dbl>   <dbl>
#> 1 Office of President Not Supervisor    69     261   0.264
#> 2 Office of President Supervisor       192     261   0.736

因此,如果您想访问管理员的百分比,您只需

list_of_all_percents$Admin$percent
#> [1] 0.8579439 0.1420561

reprex package (v0.3.0)

于 2020 年 2 月 20 日创建