I am looking to number each instance of a value in a vector as it appears. For example the first instance of a value with get '1' the second instance will get '2' and so on - counting how many this value has appeared before it in the vector. I can do this with a for loop in R using the EuStockMarkets example data in datasets.
#load data
data <- as.data.frame(datasets::EuStockMarkets)
df <- data.frame(order = 1:nrow(data),value = data$DAX)
head(df)
#calculate number of instances
start_time <- Sys.time()
for (i in 1:nrow(df)) {
df[i,"instance"]<- sum(df[1:i,"value"] == df[i,"value"])
}
end_time <- Sys.time()
end_time - start_time
#Time difference of 0.1126978 secs
This is fine but I would rather not use a for loop if there was a faster option for much larger datasets and was wondering if their was a preexisting function that - perhaps with tidyverse package.