I want to calculate the difference if the subsequent string in a column is different. Example dataset:
df <- data.frame(role = c("Mother", "Mother", "Mother", "Mother", "Child", "Mother", "Mother", "Child"),
bmi = c(22, 19, 21, 20, 17, 23, 22, 16))
For this data, if the role has switched (e.g., Mother
-> Child
or Child
-> Mother
), we calculate the difference. The expected output:
role bmi diff
Mother 22 NA
Mother 19 NA
Mother 21 NA
Mother 20 NA
Child 17 3
Mother 23 -6
Mother 22 NA
Child 16 6
How do I do this?
The suggested link Use a value from the previous row in an R data.table calculation doesn't have the matching process.