Site icon R-bloggers

How to Create a Frequency Table by Group in R?

[This article was first published on Data Science Tutorials, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

The post How to Create a Frequency Table by Group in R? appeared first on Data Science Tutorials

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

Check your inbox or spam folder to confirm your subscription.

How to Replace String in Column using R – Data Science Tutorials

The post How to Create a Frequency Table by Group in R? appeared first on Data Science Tutorials

To leave a comment for the author, please follow the link and comment on their blog: Data Science Tutorials.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.