-2

I have the following data.frame.

df <- data.frame(x = c("abc","def","def","def", "ghi", "ghi"))

How can I count the number of observation of the column?

Roman Luštrik
  • 67,056
  • 24
  • 151
  • 191
Raphael Li
  • 43
  • 4

1 Answers1

3

If the sequence by group ('x' column) is needed as the output, we can use ave from base R. We group by 'x', and get the sequence (seq_along)

with(df, ave(seq_along(x), x, FUN= seq_along))
#[1] 1 1 2 3 1 2

With dplyr, we can use row_number() after grouping by 'x'.

library(dplyr)
df %>%
    group_by(x) %>%
    mutate(Seq = row_number())
akrun
  • 789,025
  • 32
  • 460
  • 575