I would like to insert a new column in a data.frame that counts how many times a client appeared so far. But, I would like it increase by 1 each time. So, the first purchase of client A is 1, the second is 2...
In Excel you proceed with a count.if function.
I've tried this two functions, but the first ten are zero.
customer <- as.factor(sample(c("A","B","C","D"), 50, replace = TRUE, prob = c(10,20,30,40)))
purchase <- round(runif(50, 50,150),0)
purch_id <- 1:50
my_store <- data.frame(customer,purchase, purch_id)
my_store$number1 <- apply(my_store, 1, function(x)length(which(my_store$customer==x[1] & my_store$purch_id<x[3])))
my_store$number2 <- apply(my_store, 1, function(x)sum((my_store$customer==x[1] & my_store$purch_id<x[3])))
my_store
The first column is the client, the second how much he spent and the third is a unique id of each purchase. And each row is a an unique purchase two.
Thank you!