Tim Wilcox
Tim Wilcox

Reputation: 1331

Case when situation in R

Here is the sample data set and the first command that I know how to do. I want everything else that is not listed in the command to be areatype 04. I know that I could list the three out in this simple example. However, in reality I have 35 other possibilities that needed to coded as areatype 04. Is there something that I can add to the last line of code that would say "if this then 07 but if anything else then 04"

  area <- c("000995","000996","000001","000005","000998","000007")
  areatype<- c("","","","","","")

  list <- data.frame(county,areatype)

  list <- list %>% mutate(areatype=case_when(area=='000995'~'07',area=='000996'~'07')

Upvotes: 1

Views: 64

Answers (2)

LMc
LMc

Reputation: 18742

In base R you can also do this with ifelse:

list$areatype <- ifelse(list$area %in% c("000995", "000996"), "07", "04")

Alternatively, if you have a lot of area values with sequential suffixes you could do something like:

match <- grepl(paste(do.call(sprintf, list("%i$", 995:996)), collapse = "|"), list$area)
list$areatype <- ifelse(match, "07", "04")

Where the first line will return TRUE for any element of list$area that ends with 995 or 996 and FALSE otherwise.

Upvotes: 2

akrun
akrun

Reputation: 887951

We can use %in% and specify the TRUE as the else option i.e. if we don't specify the TRUE, by default it will be replaced by NA

library(dplyr)
list %>% 
   mutate(areatype = case_when(county %in% c('000995', '000996')~'07', 
          TRUE ~ '04'))

NOTE: list is a function name i.e. avoid naming objects with function names

Upvotes: 3

Related Questions