r if else for logical with logical和boollean operator

时间:2016-04-23 06:00:19

标签: r if-statement

我正在尝试使用if else语句在我的数据框中创建一个新的二进制数据列,但我得到的是全零......

命令:

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

1 个答案:

答案 0 :(得分:3)

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

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

#include <iostream>
#include <string>

using namespace std;

class Rasterizer {
protected:
        virtual string get_driver_name() const { return "???"; }
        Rasterizer();
};

class RasterizerGLES2 : public Rasterizer {
        virtual string get_driver_name() const { return "GLES2"; }
};

Rasterizer::Rasterizer() {
        cout << get_driver_name();
}

int main() {
        RasterizerGLES2();
}