Reputation: 4917
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