Home > OS >  R how to create table from dataframe containing counts over groups?
R how to create table from dataframe containing counts over groups?

Time:01-04

I have a dataframe with the count of for instance males and females for certain groups arranged in this way:

df <- data.frame (
  Round = c("R1", "R1", "R2", "R2"),
  N. = c(20, 10, 15,15),
  Gender = c("M", "F", "M","F")) 

How can I create a table accounting for counts over, for instance, Round and Gender? I would like to show the distribution of gender for each round.

I have tried


table (df$Gender, df$Round)

but this is not what I need. I need instead to show N. by groups.

CodePudding user response:

Something like this?

library(tidyr)
pivot_wider(df, names_from = Round, values_from = N.)

  Gender    R1    R2
1 M         20    15
2 F         10    15

Or in base R with reshape:

reshape(df, direction = "wide", idvar = "Gender", timevar = "Round")
  • Related