Why with() in R is doing vector operation in one case and not in the other? [duplicate]

扶醉桌前 提交于 2019-12-23 04:24:59

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!