2013-06-22 289 views
0

我有如下表:爲什麼R中的()在一種情況下做矢量操作而不是在另一種情況下?

> 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 

我需要申請使用每一行作爲變量的值下面的表達式。所以我使用()函數。這與2嵌套ifelse很好,但是當我添加第三個ifelse()它不再工作。看你自己:

> 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 

只有2個嵌套循環結果是[1] 2 2 2 2 2 2,這是我想要的。但是,當我添加第三個條件時,它不再起作用:

> 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 

爲什麼這樣做?

+0

請問,當你在第一個'ifelse'語句中使用的'&''而不是'&&使其區別? – Metrics

+0

是真棒謝謝! – Wicelo

+0

很高興它幫助你! – Metrics

回答

5

下面是一些更好代碼:

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 
相關問題