How To Use ifelse in R

Описание к видео How To Use ifelse in R

The ifelse function in R lets you perform conditional logic on vectors, doing one thing with certain values and something else with other values. It is a more efficient to use ifelse in R than it is to use explicit for loops to go through a vector and perform operations sequentially because ifelse in R is performed in a vectorized fashion, meaning the operation is carried out all at once instead of by going through each value one at a time.


Code used in this clip:

Data with bad values
data <- c(11, 7, NA, 9, NA, 13, 15, NaN, 19, 17, 14, NaN)

Use ifelse to conditionally fill bad values with the mean

ifelse(is.na(data)|is.nan(data), # logical check
mean(data, na.rm = T), # value to set if TRUE
data) # value to set if FALSE


Chaining ifelse to perform multiple operations

d <- ifelse(is.na(data)|is.nan(data), "missing",
ifelse(data < 10, "low",
ifelse(data < 15, "medium", "high")))

d
table(d)

Code Clips are basic code explanations in 3 minutes or less. They are intended to be short reference guides that provide quick breakdowns and copy/paste access to code needed to accomplish common data science tasks. Think Stack Overflow with a video explanation.


* Note: YouTube does not allow greater than or less than symbols in the text description, so the code above will not be exactly the same as the code shown in the video! For R that means I may use = for assignment and the special Unicode large < and > symbols in place of the standard sized ones for dplyr pipes and comparisons. These special symbols should work as expected for R code on Windows, but may need to be replaced with standard greater than and less than symbols for other operating systems.

Комментарии

Информация по комментариям в разработке