count the number in a grouop in r

To count the number of observations in each group in R, you can use the dplyr package's group_by() function followed by the summarize() function with the n() function inside it.

Here is an example:

main.r
library(dplyr)

# Create a mock dataset with two variables
dataset <- data.frame(
  group = rep(c("A", "B", "C"), each = 4),
  value = rnorm(12)
)

# Count the number of observations in each group
group_counts <- dataset %>%
  group_by(group) %>%
  summarize(count = n())

group_counts
286 chars
15 lines

The output will be a new dataset that shows the number of observations in each group:

main.r
# A tibble: 3 x 2
  group count
  <chr> <int>
1 A         4
2 B         4
3 C         4
88 chars
7 lines

In this example, we created a mock dataset with two variables: "group" and "value". Then we used the group_by() function to group the data by the "group" variable, followed by the summarize() function with the n() function inside it to count the number of observations in each group. Finally, we stored the results in a new dataset called "group_counts" and printed it to the console.

gistlibby LogSnag