0

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.

cliu
  • 933
  • 6
  • 13
  • Thanks for the link but I want to match strings not numbers. Also I don't see how they match the values – cliu Jun 27 '23 at 19:00
  • 1
    E.g. using `dplyr`: `mutate(df, diff = ifelse(role != lag(role), lag(bmi) - bmi, NA))` – Axeman Jun 27 '23 at 19:08

0 Answers0