Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to count the data and mutate a new column for it in R

For example my table is shown as below

Job Gender
CEO Male
Manager Male
Manager Female
Manager Male
Supervisor Female

Then I would like to organize it to something like below

Job Male Female
CEO 1 0
Manager 2 1
Supervisor 0 1

How can I make it right?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You need to group_by the Job column, then count the Gender in each Job. After that, transform the dataframe into a "wide" format by expanding the count result.

library(tidyverse)

df %>% 
  group_by(Job) %>% 
  count(Gender) %>% 
  pivot_wider(names_from = Gender, values_from = n, values_fill = 0) %>% 
  ungroup()

# A tibble: 3 × 3
  Job         Male Female
  <chr>      <int>  <int>
1 CEO            1      0
2 Manager        2      1
3 Supervisor     0      1

Or more simply, a single table function.

table(df$Job, df$Gender)

             Female Male
  CEO             0    1
  Manager         1    2
  Supervisor      1    0
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading