Creating multiple data frames using same pipes but different columns in R

Viewed 239

I have a dataset that I'd like to perform Age and Gender counts for each date and make a new dataframe to be joined together after. The workflow is like this:

age_count <- master %>%
  count(Age, Date) %>%
  pivot_wider(names_from = Age, values_from = n, values_fill = 0)%>%
  arrange(Date) 

The dataframe master contains other info such as gender in other columns. The Date column is also not unique, so add_count() doesn't work. Right now I'm repeating code for each of the columns by changing the column names (e.g. Age becomes Gender) to come up with these pivots, but I was wondering if it's possible to do this without repeating similar code by using a loop, in case I want to do more of the same pivots for more columns in the master dataframe? I'm mainly having issues with the new df assignments.

A snippet of the master dataframe looks something like this:

Date <- c("5/21","5/21","5/22","5/22","5/24","5/24","5/24")
Age <- c("70","80","70","70","60","40","40")
Gender <- c("M","M","F","M","F","M","M")
master <- data.frame(Date,Age,Gender)
1 Answers

Here is one approach which nests a call to purrr::map_dfc inside dplyr::across. It should work for all variables, but we need to convert them to factors first.

library(tidyverse)

master %>% 
  mutate(across(!Date, as.factor)) %>% 
  group_by(Date) %>% 
  summarise(across(everything(), # uses all variables, expect Date bc its the grouping var
                   ~ map_df(set_names(unique(.x)),
                    function(y) {
                      sum(y == .x, na.rm = TRUE)
                    }))
            ) %>%
  do.call("data.frame", args = .) %>% 
  replace(is.na(.), 0)

#>   Date Age.70 Age.80 Age.60 Age.40 Gender.M Gender.F
#> 1 5/21      1      1      0      0        2        0
#> 2 5/22      2      0      0      0        1        1
#> 3 5/24      0      0      1      2        2        1

Created on 2021-06-11 by the reprex package (v0.3.0)

Related