Thanks for the response firstly! I wrote my question not clear enough i think, i am trying to create the exact same table as in the image. With my dataset, i already have the year, company and value variable obtained/calculated, and i need to create the "total value cumulative in years" variable. I am trying to recreate it exactly as in the picture, so .i.e. how many times a "value" occurs in succession, but is reset when another "value" joins the company, or when a company is switched in the dataset. Also, if it would be like this, so c(1,1,1,1,1,2,2,1,1,1), the outcome would be like this: 1,2,3,4,5,1,2,1,2,3, but then as a variable To make it clearer, it's about how long an employment lasts between a firm and a partner. The "value" implies the partner, and the total value is the total duration of employment between the firm and partner. If i am understanding it correctly, what you are doing in the script is calculating how often a value occurs in a company.