RichS
RichS

Reputation: 669

A simple if else in R that creates a new column dependent on the result

I am stuck on what should be a fairly simple if else statement in R.

I have a data frame named UK that contains several columns, one of which is named location which contains the name of the UK city to which that row's data pertains.

My goal is to create a new column, named capital that will simply separate the rows into a binary London or UK ex London. I haven't done many if else statements and I'm struggling to get the syntax right, my attempt below:

if (UK$location[UK$location == "London"]) UK$capital <- "London" else UK$capital <- "UK ex London"

Should if else not be the best way to do this, I am happy to adopt a different method. Many thanks in advance for the help.

Upvotes: 1

Views: 214

Answers (1)

tospig
tospig

Reputation: 8333

As @thelatemail points out, a simple Base R solution is

UK$capital <- ifelse(location=="London", "London","UK ex London")

If you start building more complex statements then I find dplyr to be useful, and for this exmaple the solution is

## set up some data
UK <- data.frame(location=c("London","Not London"), val=c("a","b"))

library(dplyr)
UK <- UK %>%
  mutate(capital = ifelse(location=="London", "London","UK ex London"))

Upvotes: 1

Related Questions