'Multiple conditions within nested ifelse statement

Having a hard time building a nested ifelse statement where a new variable is established using an adjustment factor conditional on two existing variables.

Adjustment Dam Age | BW Adj | Male WW Adj | Female WW Adj

..... WW is adjusted based off of the Dam Age, and Sex.

Within the conditional line of the ifelse statement, I've tried "&&" - but this hasn't worked. Any ideas?

                     ifelse(data[i,"aod"]==4,2,0))))
  data[i,"adjww"]=data[i,"ww"]+
    ifelse(data[i,"aod"]>=11 && data[i,"sex"]=="HFR",18,
           ifelse(data[i,"aod"]>=11 && data[i,"sex"]=="STR",20,
                  ifelse(data[i,"aod"]==2 && data[i,"sex"]=="HFR",54,
                         ifelse(data[i,"aod"]==2 && data[i,"sex"]=="STR",60,
                                ifelse(data[i,"aod"]==3 && data[i,"sex"]=="HFR",36,
                                       ifelse(data[i,"aod"]==3 && data[i,"sex"]=="STR",40,
                                              ifelse(data[i,"aod"]==4 && data[i,"sex"]=="HFR",18,
                                                     ifelse(data[i,"aod"]==4 && data[i,"sex"]=="STR",20,0))))))))
}


Solution 1:[1]

Here's a start of a dplyr method that will be much cleaner:

library(dplyr)
data %>%
  mutate(
    gain = ww - bw,
    adjbw = bw + case_when(
      aod >= 11 ~ 3,
      aod == 2 ~ 8,
      aod == 3 ~ 5,
      aod == 4 ~ 2,
      TRUE ~ 0
    ),
    adjww = ww + case_when(
      aod >= 11 & sex == "HFR" ~ 18,
      aod >= 11 & sex == "STR" ~ 20,
      aod ==  2 & sex == "HFR" ~ 54,
      # ..., fill in more conditions
      TRUE ~ 0
    )
  )

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Gregor Thomas