0
votes

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?

nrow = dim(data)[1]
for(i in 1:nrow){
  data[i,"gain"]=data[i,"ww"]-data[i,"bw"]
  data[i,"adjbW"]=data[i,"bw"]+ifelse(data[i,"aod"]>=11,3,
                                      ifelse(data[i,"aod"]==2,8,
                                             ifelse(data[i,"aod"]==3,5,
                                                    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))))))))
}

Below is the desired output.

     id aod       dob sex bw        wwd  ww  hip gain adjbW adjww
1 H0001   5 4/25/2020 HFR 64 11/17/2020 496 41.5  432    64    NA
2 H0002   4 4/25/2020 HFR 70 11/17/2020 494 41.5  424    72    NA
3 H0003   4 4/25/2020 HFR 56 11/17/2020 508 40.5  452    58    NA
4 H0004   4 4/26/2020 HFR 66 11/17/2020 474 38.5  408    68    NA
5 H0005   6 4/26/2020 STR 76 11/18/2020 562 42.5  486    76    NA

1
What is i? You should not use ifelse() inside a loop, but instead if() and else. Provide a reproducible example including your current code and what you expect the result to look like. There is surely a much easier way to do this. The best way to provide data is to use the dput() function on a subset of your actual data. - dcarlson
Please share a reproducible dataset using the dput function. Here is how: youtu.be/3EID3P1oisg - Shawn Hemelstrand

1 Answers

2
votes

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
    )
  )