Convert values below a threshold into 1

前端 未结 3 584
离开以前
离开以前 2021-01-13 19:47

Let\'s say if I have the following data

x <- rnorm(100)

I want to create another column where where if x is equal to or gre

相关标签:
3条回答
  • 2021-01-13 20:18

    We can create the logical condition and wrap with +

    xNew <- +(x >=0.2)
    

    If we need a data.frame,

    dat <- data.frame(x, xNew)
    

    Or use ifelse

    xNew <- ifelse(x >= 0.2, 1, 0) 
    
    0 讨论(0)
  • 2021-01-13 20:22

    Doing this for the benefit of the Colonel:

    library(microbenchmark)
    
    set.seed(1492)
    x <- rnorm(10000)
    
    microbenchmark(asi=as.integer(x >= 0.2),
                   asn=as.numeric(x >= 0.2),
                   pls=+(x >=0.2),
                   hsd=Heaviside(x, 0.2))
    
    ## Unit: microseconds
    ##  expr    min      lq      mean  median      uq      max neval cld
    ##   asi 18.351 20.7575  27.88867 22.4250 22.8695  598.206   100  a 
    ##   asn 23.710 25.9740  32.77422 29.2405 29.9860  340.234   100  a 
    ##   pls 17.989 20.2640  26.07038 22.6855 23.3020  320.443   100  a 
    ##   hsd 88.493 92.2145 148.17850 94.1935 95.5250 2831.695   100   b
    

    Heaviside is totally not what you want to be doing if you care at all about performance. And, it's just doing:

    function (x, a = 0) {
      result = (sign(x - a) + 1)/2
      result
    }
    

    anyway.

    0 讨论(0)
  • 2021-01-13 20:29

    You want to use an Heaviside function. You can find it in the fbasics package, for example.

    set.seed(42)
    x <- rnorm(100)
    library(fBasics)
    Heaviside(x, 0.2)
    
    0 讨论(0)
提交回复
热议问题