binarize: Binarize a vector

View source: R/binarize.R

binarizeR Documentation

Binarize a vector

Description

This function transforms a vector to a vector composed of zeros and ones.

Usage

binarize(x, zero = NA, one = "else", drop, output = c(0, 1))

Arguments

x

The vector to binarize

zero

The pattern of zeros to be find in x. By default, set to NA. Can be anything.

one

The pattern of ones to be find in x. By default, set to "else", which means all that is not of the zero pattern. Otherwise, can be anything.

drop

If there are values not fitting both previous patterns, theses values are returned to NA. By default (drop=TRUE), these NA are left in the output vector. If you want to discard them, please specify drop=TRUE.

output

The output of the binarization. By default to 0/1, but it can be changed with a vector or a list of length 2.

Details

For given zero and one 'templates', the function transforms each one in zero or in one and return a 0/1 vector.

Value

The binarized vector of the input vector, with only 0 and 1 (and NA if applicable).

Examples


set.seed(1)
x<-runif(100,0,1) # Create a vector of random values
x[as.integer(runif(10,1,100))]<-NA # Randomly replace some of these by NA's
binarize(x) # Binarize it with default option
all(which(is.na(x))==which(binarize(x)==0)) # Check if all NA are zero
all(which(!is.na(x))==which(binarize(x)==1)) # Check if all non-NA are one

x<-c(rep(0,20),2,rep(1,20)) # Create a vector with three repeated numbers: 0, 1, and 2
binarize(x,zero=0,one=1) # Binarize it by saying that zeros are 0, and ones are 1 (thus, two is not allocated, and it is replaced by NA)
binarize(x,zero=0,one=1,drop=TRUE) # Dropping the NA value (which are the no 0 or 1)
length(x) # How many numbers are in x
length(binarize(x,zero=0,one=1)) # How many numbers if we binarize with default (normally, same length than x, because the 2 is replaced by NA)
length(binarize(x,zero=0,one=1,drop=FALSE)) # If we decide do don't drop, the NA is still there, but there is no warnings
length(binarize(x,zero=0,one=1,drop=TRUE)) # If we decide to drop, the NA is removed, and the length is shorter of one


jacobmaugoust/ULT documentation built on May 16, 2023, 1:29 p.m.