2016-04-23 72 views
1

我試圖使用if else語句在我的數據幀創建二進制數據的新列,但我所得到的循環是全零...R如果別人用邏輯和boollean運營商

命令:

for(i in 1:nrow(asort)){ 
    if(asort$recip==0 && asort$dist<.74){ 
    asort$temp[i]<-0 
    } else{ 
    asort$temp[i]<-1 
    } 
} 

#temp ends up being all 0's 

此外,我真的想問沿此線的東西:

# if the data in the recip column = 0, and the distances is < 0.74, OR if the #data is greater than 1.85 give me a zero, else 1 

for(i in 1:nrow(asort)){ 
if(asort$recip==0 && asort$dist<.74 || asort$dist>1.85){ 
    asort$temp[i]<-0 
    } else{ 
    asort$temp[i]<-1 
    } 
} 


> head(asort) 
      coordinates CLASS_ID Flight UFID  dist nnid nnid2 observed recip temp 
157 (285293.3, 4426017)  0 F4_ F4_156 0.3857936 158 F4_157  0  0 0 
158 (285293.2, 4426017)  0 F4_ F4_157 0.3857936 157 F4_156  0  0 0 
259 (285255, 4426014)  0 F4_ F4_258 0.5226039 261 F4_260  1  0 0 
261 (285255, 4426014)  0 F4_ F4_260 0.5226039 259 F4_258  1  0 0 
402 (285275.3, 4426004)  0 F4_ F4_401 0.5598427 403 F4_402  1  0 0 
403 (285275.6, 4426004)  0 F4_ F4_402 0.5598427 402 F4_401  1  0 0 
+0

您需要將計數器添加到布爾檢查。例如,'asort $ recip'應該是'asort $ recip [i]'。 – Gschneider

+0

我當時希望這件事很簡單 - 謝謝! – user6243485

+0

將來,您應該提供一個可重複的示例。 – aelwan

回答

3

使用df data.frame

dist <- runif(10, 0.3, 2) 
recip<- c(0,1,1,0,1,0,1,0,0,1) 
df <- data.frame(dist, recip) 

ifelse

df$temp<-ifelse(df$dist < 0.74 & df$recip == 0 , 0, 
       ifelse(df$dist > 1.85 & df$recip == 0, 0, 1)) 

> head(df) 
#  dist recip temp 
#1 1.1878002  0 1 
#2 0.4147835  1 1 
#3 1.3707311  1 1 
#4 0.9008034  0 1 
#5 1.0220149  1 1 
#6 1.9384069  0 0