问题
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 ?
回答1:
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
来源:https://stackoverflow.com/questions/17252466/why-with-in-r-is-doing-vector-operation-in-one-case-and-not-in-the-other