IF Loop in R for finding the position of column

dataexploration
r

#1

Hello,

I have a dataset from which I am trying to find out the column positions based on the outcome(this variable goes into a function).Outcome can be of three types- “heart attack”,“heart failure” & “pneumonia”.

I had previously used if in this way:
pos <- if (outcome == “heart attack”)
grep("^Hospital.30.Day.Death…Mortality…Rates.from.Heart.Attack$",colnames(hospital))

pos <- if (outcome == “heart failure”)
grep("^Hospital.30.Day.Death…Mortality…Rates.from.Heart.Failure$",colnames(hospital))

pos <- if (outcome == “pneumonia”)
grep("^Hospital.30.Day.Death…Mortality…Rates.from.Pneumonia$",colnames(hospital))

However this did not work and pos always returned NULL.

Then I used if else:
pos <- if (outcome == “heart attack”) {
grep("^Hospital.30.Day.Death…Mortality…Rates.from.Heart.Attack$",colnames(hospital))
}
else if (outcome == “heart failure”) {
grep("^Hospital.30.Day.Death…Mortality…Rates.from.Heart.Failure$",colnames(hospital))
}
else {
grep("^Hospital.30.Day.Death…Mortality…Rates.from.Pneumonia$",colnames(hospital))
}

This worked great.
However,what I am not understanding is in the previous case why is the code not working.
Any input is greatly appreciated.
PS:The question might be silly,but I have no idea(My exp is R is 1 month)


#2

the first format is basically searching for ALL conditions to be true ( which cant be) while the second one is searching for one condition to be true.

NOTE I cant really say because you need to atleast show 4 lines of data to enable us to run the code. for it to be truly reproducible


#3

Hello @ajay_ohri sir,

I should have attached a copy of the data,my bad!

Note.The columns 2 & 3 are named as in the code.Here i have renamed them to prepare this data.