r - Create counter with multiple variables -
this question has answer here:
i have data looks below:
customerid tripdate 1 1/3/2013 1 1/4/2013 1 1/9/2013 2 2/1/2013 2 2/4/2013 3 1/2/2013
i need create counter variable, below:
customerid tripdate tripcounter 1 1/3/2013 1 1 1/4/2013 2 1 1/9/2013 3 2 2/1/2013 1 2 2/4/2013 2 3 1/2/2013 1
tripcounter
each customer.
use ave
. assuming data.frame
called "mydf":
mydf$counter <- with(mydf, ave(customerid, customerid, fun = seq_along)) mydf # customerid tripdate counter # 1 1 1/3/2013 1 # 2 1 1/4/2013 2 # 3 1 1/9/2013 3 # 4 2 2/1/2013 1 # 5 2 2/4/2013 2 # 6 3 1/2/2013 1
for it's worth, implemented version of approach in function included in "splitstackshape" package. function called getanid
:
mydf <- data.frame(ida = c("a", "a", "a", "b", "b", "b", "b"), idb = c(1, 2, 1, 1, 2, 2, 2), values = 1:7) mydf # install.packages("splitstackshape") library(splitstackshape) # getanid(mydf, id.vars = c("ida", "idb")) getanid(mydf, id.vars = 1:2) # ida idb values .id # 1 1 1 1 # 2 2 2 1 # 3 1 3 2 # 4 b 1 4 1 # 5 b 2 5 1 # 6 b 2 6 2 # 7 b 2 7 3
as can see example above, i've written function in such way can specify 1 or more columns should treated id columns. checks see if of id.vars
duplicated, , if are, generates new id variable you.
Comments
Post a Comment