Jack Armstrong
Jack Armstrong

Reputation: 1249

Define leading counter for sequence in R

I am trying to create a numerical sequence in R that looks like this:

ID|class|counter
 A|   z|    1
 A|   z|    2
 A|   c|    1
 A|   c|    2
 A|   z|    3
 B|   z|    1
 B|   c|    1
 B|   c|    2

So the Id is unique and I want to know which order each observation is in given their class. I am trying to count the inner class-Id combination. How does one do this?

Upvotes: 1

Views: 37

Answers (2)

ThomasIsCoding
ThomasIsCoding

Reputation: 101508

A base R option using ave

within(
  df,
  counter <- ave(1:nrow(df), ID, class, FUN = seq_along)
)

or a data.table option

setDT(df)[, counter := seq(.N), by = names(df)]

Upvotes: 0

akrun
akrun

Reputation: 887148

Here is an option

library(dplyr)    
df1 %>% 
   group_by(ID, class) %>%
   mutate(counter = row_number())

-output

# A tibble: 8 x 3
# Groups:   ID, class [4]
#  ID    class counter
#  <chr> <chr>   <int>
#1 A     z           1
#2 A     z           2
#3 A     c           1
#4 A     c           2
#5 A     z           3
#6 B     z           1
#7 B     c           1
#8 B     c           2

Or with data.table

setDT(df1)[, counter := rowid(ID, class)]

data

df1 <- structure(list(ID = c("A", "A", "A", "A", "A", "B", "B", "B"), 
    class = c("z", "z", "c", "c", "z", "z", "c", "c"), counter = c(1L, 
    2L, 1L, 2L, 3L, 1L, 1L, 2L)), class = "data.frame", row.names = c(NA, 
-8L))

Upvotes: 1

Related Questions