I would like to replace values in previous row(s) conditional on values in other columns.
This is an example of my data that has minutes/day spent in various activities.
activity <- c("car","soccer","eat","drink")
category <- c("travel","sport","eat/drink","eat/drink")
duration <- c(75,15,10,160)
df <- data.frame(activity, category,duration)
activity category duration
1 car travel 75
2 soccer sport 15
3 eat eat/drink 5
4 drink eat/drink 160
If in any row, duration of "drink" is > 5 minutes (as it is in row 4), I want to replace "duration" in that row with 5 minutes, and add the remaining time (in this case 155 minutes) to the "duration" value in the preceding row, UNLESS the preceding row has "eat/drink" as its "category", in which case I want to add the remaining time to "duration" of the row before the preceding row...
In the above example, I would add 155 minutes to "duration" in row 2. However, if row 2 also had "eat/drink" as its "category", I would want to add the 155 minutes to the preceding row (row 1).
Thanks for any help!
Aucun commentaire:
Enregistrer un commentaire