How to Create a Frequency Table by Group in R?
How to Create a Frequency Table by Group in R?, To produce a frequency table by the group in R, use the dplyr package’s following functions.
Reorder Boxplots in R with Examples »
How to Create a Frequency Table by Group in R
Let’s say we have the R data frame shown below,
df <- data.frame(team=c('P1', 'P1', 'P1', 'P2', 'P2', 'P3', 'P3', 'P3'), position=c('R1', 'R3', 'R2', 'R2', 'R1', 'R1', 'R2', 'R1'))
Now we can view the data frame
df
team position 1 P1 R1 2 P1 R3 3 P1 R2 4 P2 R2 5 P2 R1 6 P3 R1 7 P3 R2 8 P3 R1
Let’s say that we want to make a table of frequencies that lists the frequency of each position, sorted by team.
To do this, we can use the syntax shown below.
library(dplyr)
compute position frequency, grouped by team.
How to create contingency tables in R? – Data Science Tutorials
df %>% group_by(team, position) %>% summarize(Freq=n())
team position Freq <chr> <chr> <int> 1 P1 R1 1 2 P1 R2 1 3 P1 R3 1 4 P2 R1 1 5 P2 R2 1 6 P3 R1 2 7 P3 R2 1
How to interpret the result is as follows:
1 player on team P1 has position ‘R1’
1 player on team P1 have position ‘R2’
And so on…
Keep in mind that by modifying the variable name in the summarise() method, we can rename the column that contains the frequencies.
We could, for instance, change the column’s name to “count” instead.
Best Books to Learn R Programming – Data Science Tutorials
library(dplyr)
compute position frequency, grouped by team.
df %>% group_by(team, position) %>% summarize(count=n())
team position count <chr> <chr> <int> 1 P1 R1 1 2 P1 R2 1 3 P1 R3 1 4 P2 R1 1 5 P2 R2 1 6 P3 R1 2 7 P3 R2 1
How to Replace String in Column using R – Data Science Tutorials