I want to create a table in R that looks something like this:

I have tried many different approaches using dplyr and basic R but nothing looks like I want it to.
Here is an example of my dataframe:
| Country | Gender | Income |
|---|---|---|
| Country 1 | F | Inc1 |
| Country 1 | F | Inc2 |
| Country 2 | F | Inc2 |
| Country 1 | M | Inc1 |
| Country 2 | M | Inc3 |
| Country 3 | F | Inc3 |
| Country 3 | M | Inc2 |
There might be a solution using
group_byandsummarisewithacross, but times when it's hard to find those, you can turn to the more flexible option ofgroup_splitandpurrr::map.Obs:
country = x$Country[1]is just a shortcut to save the current group's country. Later, we use that variable to create the columns for 'freq' and 'prop' with the country name first, using the 'glue' package syntax:'{country} freq' :=.Just to make it clearer to see what's happening, here's the tibble created in one of the iterations (for 'Country 1' and 'Gender'):
The map's are creating one of these for every country and every variable, and later we are joining them all with the
reduce(full_join)Result:
Dummy data: