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
i? You should not useifelse()inside a loop, but insteadif()andelse. 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 thedput()function on a subset of your actual data. - dcarlsondputfunction. Here is how: youtu.be/3EID3P1oisg - Shawn Hemelstrand