# How to count the number of rows by variable in R

Context: I am trying to determine a way to create an extra step in between my dataset and the code below or optimise the code altogether. Currently, the data frame "df_b" looks as follows. In column 4, the repetitions exceed 1 (as they denote the number of times a word appears +/- 5 words of a term.

Problem: I am trying to count the number of lemmas that appear within each year and create a tibble. This is what I have tried to do below but I realise now that I am not doing so as some rows in repetition exceed 1.

Possible solution 1: create another column for each rows holding the value 1, then input into code below Possible solution 2: create new tibble by grouping by year and counting the number of lemmas in each year (not sure how to code this one up)

# sum the repetitions of words by year
sum_repeat_b <- aggregate(df_b[, 4], list(df_b\$year), sum)
sum_repeat_b <- dplyr::rename(sum_repeat_b, "year"="Group.1")
sum_repeat_b <- dplyr::rename(sum_repeat_b, "sum_repeat_b"="x")

show(sum_repeat_b)

• Can you please post the data with dput()? Dec 20, 2021 at 8:17

Would the following work for you? The following code should count the number of unique values in the lemma column within each group based on the year column.
library(dplyr)