simple if statement in R with ifelse

Posted on: October 28, 2017 Posted by: Guy Manova Comments: 0

simple if statement in R with ifelse

Simple if statement in R with ifelse

Let’s see how to create the equivalent of Excel’s simple if statement in R using the ifelse function in base R and with dplyr:

In Excel:

simple if statement in R with ifelse

 

In R:

# pre-session options

rm(list = ls())
#getwd()
#setwd(“C:\\Users\\User\\Documents”)

 

if (!require(dplyr)) install.packages(‘dplyr’)
library(dplyr)

campaigns <- read.csv(“https://www.dropbox.com/s/gv83asx8qeuog0z/google%20campaigns.csv?dl=1”)
write.csv(campaigns, “campaigns.csv”)

 

# let’s create a simple bin for the campaign spend, either “material” or “negligible” base
# on the cost:

campaigns$size <- ifelse(campaigns$Cost >= 500, “material”, “negligible”)

campaigns

simple if statement in R with ifelse

# lets see how this can look with dplyr

campaigns$size = NULL #deletes the column

campaigns <- campaigns %>%
mutate(size = if_else(campaigns$Cost >= 500, “material”, “negligible”))

simple if statement in R with ifelse

you can look at more a more complex of nested ifs here.

Leave a Reply:

Your email address will not be published. Required fields are marked *