EmilieK EmilieK - 25 days ago 5x
R Question

Repeating ifelse statement on row in dataframe or using ifelse-statement on a vector with multible factors

Hope someone can help with this problem in R-studio

I'm having a dataset (df) that in a bit simplified looks like this

Resp Status Threshold
1 16 3
0 134 4
1 3.5 3

I would like to perform this ifelse-test on each of the rows

CR.Wat=ifelse(Threshold!="NA" && Status!="NA",ifelse(Resp!=1,Threshold/Status,Status/Threshold),"")

I expect to get three values of Threshold/Status. But instead I get only one value.

I assume I should somehow tell the that I would like it for each of the rows.

I tried to do this by using this formula

CR.Wat=ifelse(c(Threshold)!="NA" && c(Status)!="NA",ifelse(c(Resp)!=1,c(Threshold/Status),c(Status/Threshold)),"")

But this did not affect anything.

Can anyone help me?


Your operation only returned one value because you used && instead of &. You can read about the difference between these two operators at ?"&".

That being said, your operation can be done without the use of a nested ifelse by noticing that you want Threshold/Status (aka (Threshold/Status)^1) when Resp != 1 and Status/Threshold (aka (Threshold/Status)^(-1)) when Resp == 1.

with(dat, (Treshold / Status)^(1-2*(Resp == 1)))
# [1] 5.33333333 0.02985075 1.16666667