I'm trying to get the maximum value BY ROW across several columns (climatic water deficit -- def_59_z_#
) depending on how much time has passed (time since fire -- YEAR.DIFF
). Here are the conditions:
- If 1 year has passed, select the deficit value for first year.
(
def_59_z_1
). - If 2 years: max deficit of first 2 years.
- If 3 years: max of deficit of first 3 years.
- If 4 years: max of deficit of first 4 years.
- If 5 or more years: max of first 5 years.
However, I am unable to extract a row-wise max when I include a condition. There are several existing posts that address row-wise min and max (examples 1 and 2) and sd (example 3) -- but these don't use conditions. I've tried using apply
but I haven't been able to find a solution when I have multiple columns involved as well as a conditional requirement.
The following code simply returns 3.5 in the new column def59_z_max15
, which is the maximum value that occurs in the dataframe -- except when YEAR.DIFF
is 1, in which case def_50_z_1
is directly returned. But for all the other conditions, I want 0.98, 0.67, 0.7, 1.55, 1.28 -- values that reflect the row maximum of the specified columns. Link to sample data here. How can I achieve this?
I appreciate any/all suggestions!
data <- data %>%
mutate(def59_z_max15 = ifelse(YEAR.DIFF == 1,
(def59_z_1),
ifelse(YEAR.DIFF == 2,
max(def59_z_1, def59_z_2),
ifelse(YEAR.DIFF == 3,
max(def59_z_1, def59_z_2, def59_z_3),
ifelse(YEAR.DIFF == 4,
max(def59_z_1, def59_z_2, def59_z_3, def59_z_4),
max(def59_z_1, def59_z_2, def59_z_3, def59_z_4, def59_z_5))))))