for loop - I want to do calculation between different items when id is the same in R -


i have following data.

id  type   1   15 1   16 2   10 3   10 3   11 3   13 3   14 4   9 5   8 5   20 5   21 5   22 

using above data, want calculate "interval" when "id" equal.

id  type interval 1   15    - 1   16    1 2   10    - 3   10    - 3   11    1 3   13    2 3   14    1 4   9     - 5   8     - 5   20    12 5   21    1 5   22    1 

we group 'id' , take diff create 'interval' column

library(data.table) setdt(df1)[, interval := c(0, diff(type)), = id] 

or dplyr

library(dplyr) df1 %>%     group_by(id) %>%     mutate(interval = c(0, diff(type)) 

or ave base r

df1$interval <- with(df1, ave(type, id, fun = function(x) c(0, diff(x)))) 

Comments

Popular posts from this blog

neo4j - finding mutual friends in a cypher statement starting with three or more persons -

php - How to remove letter in front of the word laravel -

minify - Minimizing css files -