anrisakaki96
anrisakaki96

Reputation: 313

How can I use a for-loop to summarise data as a new dataframe?

My code to summarise data looks like this:

sec_02 <- employment_mf_02 %>%
  select(sex, industry, hhwt) %>% 
  group_by(industry) %>% 
  count(industry, sex, wt = hhwt) %>% 
  pivot_wider(names_from = "sex", values_from = "n") %>% 
  mutate(Industry_sum = Male + Female,
         Msec = Male / Industry_sum,
         Fsec = Female / Industry_sum)

sec_04 <- employment_mf_04 %>%
  select(sex, industry, hhwt) %>% 
  group_by(industry) %>% 
  count(industry, sex, wt = hhwt) %>% 
  pivot_wider(names_from = "sex", values_from = "n") %>% 
  mutate(Industry_sum = Male + Female,
         Msec = Male / Industry_sum,
         Fsec = Female / Industry_sum)

sec_06 <- employment_mf_06 %>%
  select(sex, industry, hhwt) %>% 
  group_by(industry) %>% 
  count(industry, sex, wt = hhwt) %>% 
  pivot_wider(names_from = "sex", values_from = "n") %>% 
  mutate(Industry_sum = Male + Female,
         Msec = Male / Industry_sum,
         Fsec = Female / Industry_sum)

I understand that I can put employment_mf_xx in a list and use a for-loop to do this. However, this would change the underlying data, but I want to create new dataframes sec_02 sec_04 and sec_06. Is there a way I can do this?

Thank you.

Upvotes: 0

Views: 25

Answers (1)

Onyambu
Onyambu

Reputation: 79318

list(sec02 = employment_mf_02, sec04 = employment_mf_04, sec06 = employment_mf_06) %>%
  bind_rows(.id = 'grp') %>%
  select(grp, sex, industry, hhwt) %>% 
  group_by(grp, industry) %>% 
  count(industry, sex, wt = hhwt) %>% 
  pivot_wider(names_from = "sex", values_from = "n") %>% 
  mutate(Industry_sum = Male + Female,
         Msec = Male / Industry_sum,
         Fsec = Female / Industry_sum) %>%
  ungroup() %>%
  group_by(grp) %>%
  group_split(.keep = FALSE) %>%
  list2env(.GlobalEnv)

Now call sec02

Upvotes: 1

Related Questions