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