dimanche 1 décembre 2019

Conditional subtraction of row values based on 2 conditions

I have a long-form dataframe subsetted below. What I need to do is adjust the value column based on both the Response and Date columns. I need to adjust the value column for rows where Response = Photosynthesis. If Response = Photosynthesis, I need to subtract the value where Response = Respiration. I also have repeated measures on different dates so the Respiration and Photosynthesis values need to be from the same date. I think ifelse will work but I can't get the syntax right.

test <- structure(list(variable = c(221L, 221L, 44L, 44L, 221L, 221L, 44L, 44L), value = 
c(-1.21625718690742, 1.15247376323723, -0.374982444111372, -0.1080667523228, 
-0.344666861319387, 0.453100231803574, -0.200976470494833, 0.100700409657002), Date = 
structure(c(18155, 18155, 18155, 18155, 18171, 18171, 18171, 18171), class = "Date"), 
Response = c("Respiration", "Photosynthesis", "Respiration", "Photosynthesis", "Respiration", 
"Photosynthesis", "Respiration", "Photosynthesis")), row.names = c(NA, -8L), groups = 
structure(list(variable = c(44L, 44L, 221L, 221L), Date = structure(c(18155, 18171, 18155, 
18171), class = "Date"), .rows = list(3:4, 7:8, 1:2, 5:6)), row.names = c(NA, -4L), class = 
c("tbl_df", "tbl", "data.frame"), .drop = TRUE), class = c("grouped_df", "tbl_df", "tbl", 
"data.frame"))

Aucun commentaire:

Enregistrer un commentaire