Percentage-Crosstable grouped by third variable

Viewed 27

I have a (for me) rather complicated question and don't really know how to describe it. Sorry if there already is a solution to this I didn't find!

Let's say I have a dataframe with the amount of years people stayed at their parents home, their mothers education status and sample year.

df <- data.frame(years = c(3,2,3,3,2,3,1,3,1,3), 
                 edu = c(3,3,2,1,2,1,3,2,1,2), 
                 sample = c(2000, 2005, 2000,2005, 2000, 2005, 2000, 2005, 2000, 2005))
                 

I want to make a crosstable between the percentage of people staying with their parents for 3 years and their mothers education status, but sorted by sample year, so that in the end I have a table that can show period-effects but is still controlling for education status.

I tried and failed using various aggregate, filter and if_any ideas, but they all failed in (at least) one regard.

Any help would be appreciated!

1 Answers

Best if you provided an example for what you want the end result to be, but my guess is something along these lines?

library(tidyverse)

df <- data.frame(
  years = c(3,2,3,3,2,3,1,3,1,3),
  edu = c(3,3,2,1,2,1,3,2,1,2),
  sample = c(2000, 2005, 2000,2005, 2000, 2005, 2000, 2005, 2000, 2005)
)

df %>% 
  group_by(sample) %>% 
  mutate(three = (years == 3)/n()) %>% 
  group_by(sample, edu) %>% 
  summarise(three_prop = sum(three))
#> `summarise()` has grouped output by 'sample'. You can override using the
#> `.groups` argument.
#> # A tibble: 6 × 3
#> # Groups:   sample [2]
#>   sample   edu three_prop
#>    <dbl> <dbl>      <dbl>
#> 1   2000     1        0  
#> 2   2000     2        0.2
#> 3   2000     3        0.2
#> 4   2005     1        0.4
#> 5   2005     2        0.4
#> 6   2005     3        0
Related