0

I have the following table :

> head(datalist[[5]])
       X5CO     X5CS     X5CD   X5CSD
1  24.87769 24.31233 26.84647 34.3316
2  24.74026 24.31233 26.84647 34.3316
3  24.45217 24.31233 26.84647 34.3316
10 24.87769 24.31233 26.15139 34.3316
11 24.74026 24.31233 26.15139 34.3316
12 24.45217 24.31233 26.15139 34.3316

I need to apply the following expression using every row as variable values. So I'm using with() function. This is working well with 2 nested ifelse, but when I add a third ifelse() it doesn't work anymore. See by yourself :

> with( head(datalist[[5]]),{
+   cCO=get(paste("X", 5,"CO",sep=""))
+   cCS=get(paste("X", 5,"CS",sep=""))
+   cCD=get(paste("X", 5,"CD",sep=""))
+   cCSD=get(paste("X", 5,"CSD",sep=""))
+           ifelse( (cCS-cCO) > 0, 1,  #1st consequent
+                   ifelse ( (cCD-cCO) > 0, 2, # 2nd
+                            5) ) } )  # default
[1] 2 2 2 2 2 2

With only 2 nested loops the result is [1] 2 2 2 2 2 2 and it is what I want. However when I add a third condition it doesn't work anymore :

> with( head(datalist[[5]]),{
+   cCO=get(paste("X", 5,"CO",sep=""))
+   cCS=get(paste("X", 5,"CS",sep=""))
+   cCD=get(paste("X", 5,"CD",sep=""))
+   cCSD=get(paste("X", 5,"CSD",sep=""))
+       ifelse( (cCS-cCO)>0 && (cCD-cCO) > 0, 3, #1st consequent
+         ifelse( (cCS-cCO) > 0, 1,  #2nd consequent
+           ifelse ( (cCD-cCO) > 0, 2, # 3rd
+                        5) ) ) } )  # default
[1] 2

Why is it doing this ?

Wicelo
  • 2,358
  • 2
  • 28
  • 44
  • Does it make difference when you use `&` instead of `&&` in first `ifelse` statement? – Metrics Jun 22 '13 at 15:59
  • For the difference between `&` and `&&`, see [here](http://stackoverflow.com/questions/6558921/r-boolean-operators-and) – Metrics Jun 22 '13 at 16:21
  • 1
    It is painfully obvious that your background is in another language and you are new to R. Reading your code almost hurts. – Roland Jun 22 '13 at 16:26

1 Answers1

5

Here is some nicer code:

DF <- read.table(text="X5CO     X5CS     X5CD   X5CSD
1  24.87769 24.31233 26.84647 34.3316
2  24.74026 24.31233 26.84647 34.3316
3  24.45217 24.31233 26.84647 34.3316
10 24.87769 24.31233 26.15139 34.3316
11 24.74026 24.31233 26.15139 34.3316
12 24.45217 24.31233 26.15139 34.3316",header=TRUE)

#clean-up column names
names(DF) <- gsub("X5","c",names(DF))

#logicals get converted to numerics, when doing calculations with them
with(DF,(cCO<cCS) + (cCO<cCD)*2 + (cCO>=cCS & cCO>=cCD)*5)
#[1] 2 2 2 2 2 2
Roland
  • 127,288
  • 10
  • 191
  • 288