-1

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
  • 69,533
  • 24
  • 154
  • 197
Raphael Li
  • 53
  • 4

1 Answers1

4

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
  • 874,273
  • 37
  • 540
  • 662