r - Create a sequential number (counter) for rows within each group of a dataframe -
this question has answer here:
how can generate unique id numbers within each group of dataframe? here's data grouped "personid":
personid date measurement 1 x 23 1 x 32 2 y 21 3 x 23 3 z 23 3 y 23
i wish add id column unique value each row within each subset defined "personid", starting 1
. desired output:
personid date measurement id 1 x 23 1 1 x 32 2 2 y 21 1 3 x 23 1 3 z 23 2 3 y 23 3
i appreciate help.
the misleadingly named ave()
function, argument fun=seq_along
, accomplish nicely -- if personid
column not strictly ordered.
df <- read.table(text = "personid date measurement 1 x 23 1 x 32 2 y 21 3 x 23 3 z 23 3 y 23", header=true) ## first data.frame ave(df$personid, df$personid, fun=seq_along) # [1] 1 2 1 1 2 3 ## another, in personid *not* in order df2 <- df[c(2:6, 1),] ave(df2$personid, df2$personid, fun=seq_along) # [1] 1 1 1 2 3 2
Comments
Post a Comment