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")

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

1 Answer 1


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.


df %>%
    group_by(year) %>%
    summarise(count = n_distinct(lemma))
  • $\begingroup$ Thank you Ox--that is exactly what I needed! I clearly need to learn to use dplyr and tidyr package. In this example, what is tidyr used for? $\endgroup$
    – n.baes
    Dec 21, 2021 at 8:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.