theforestecologist
theforestecologist

Reputation: 4917

How to sequentially number a vector in R based on changing unique values?

Assume I have the following vector:

dat <- c(1,1,1, 2,2,2, 3,3, 4,4,4,4)   <- (I added spaces to better see grouping)

I would like to assign sequential numbers starting with 1 restarting for each unique value in dat. The desired result would be:

1 2 3   1 2 3   1 2   1 2 3 4    <- (I added spaces to better see grouping)

My attempt:

unlist(
  lapply(unique(dat), function(x) 
     seq(1,length(which(dat==x)==T),1)
  )
)

[1] 1 2 3 1 2 3 1 2 1 2 3 4

Is there a more straightforward way to do this?

Upvotes: 3

Views: 669

Answers (1)

joran
joran

Reputation: 173577

Yes:

sequence(rle(dat)$lengths)

Upvotes: 3

Related Questions