I am struggling to number subgroups in a dataframe.
Let's take iris
dataset for example.
Let's say that iris$Species
identifies my subgroups (so I have three subgroups: setosa
, versicolor
, virginica
). Now I would like to add another column to iris, let's say numer of observations: iris$Obs
. And for each of the subgroups, I'd like to have numbers, from 1 to the length of a subgroup, that resets to 1 when the subgroup changes.
In other words, I'd like the "Obs
" to start at 1 whenever "Species
" changes and increment by one, as long as "Species
" is the same.
I prepared an image, but being a complete noob I have no reputation points to paste it here...
Thank everyone for help!
EDIT: > dput(iris)
structure(list(Species = structure(c(1L, 1L, 1L, 2L, 2L, 3L), .Label = c("setosa",
"versicolor", "virginica"), class = "factor")), .Names = "Species", row.names = c(NA,
-6L), class = "data.frame")