Convert values ​​below threshold to 1

Say if I have the following data

x <- rnorm(100)

I want to create another column where if xis equal to or greater than 0.2, give it a value of 1 or otherwise.

+4
source share
3 answers

We can create a logical condition and wrap using +

xNew <- +(x >=0.2)

If we need to data.frame,

dat <- data.frame(x, xNew)

Or use ifelse

xNew <- ifelse(x >= 0.2, 1, 0) 
+6
source

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

set.seed(42)
x <- rnorm(100)
library(fBasics)
Heaviside(x, 0.2)
+6
source

:

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 , , . :

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

.

+6

Source: https://habr.com/ru/post/1610255/


All Articles