user6243485
user6243485

Reputation: 11

r if else for loop with logical and boollean operators

I'm trying to use an if else statement to create a new column of binary data in my data frame, but what I get is all zeros...

command:

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

In addition, I would actually like to ask something along the lines of this:

# 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

Upvotes: 1

Views: 118

Answers (1)

shiny
shiny

Reputation: 3502

Using 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)

and 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

Upvotes: 3

Related Questions