Want to create a column using ifelse based on five differing statements.
Statements:
- If state = "N" and "region_1" is "00" or "99", paste "region_2"
- If state = "N" and "region_1" is NOT "00" or "99", paste "region_1"
- If state = "T", paste "region_1"
- If state = "3", paste "region"
- If state = "W" and "region_1" is NOT "ED", "FL", "SG", "SY", "XP", "AL", "AG", "EB" or "AB", paste "region_1"
Mock data:
state = c("T","3","W", "W","W","W","W","N","N","N","Q","Q","N","Q")
region = c("CD","AB","IC","IS", "IE", "IF", "IA", "A2", "A9", "A9", "GW", "AW", "K0", "DW")
region_1 = c("DG","BC","CL","SY","ED", "FL", "AL", "23", "99", "99", "WB", "WD", "02", 'WW')
region_2 = c("00", "D1", "05", "00", "00", "01", "59", "00", "23", "24", '03', "03", "37", "03")
a <- data.frame(state, region, region_1, region_2)
My attempt to solve:
library(dplyr)
b <- a %>% mutate(t = ifelse(state == "N" & region_1 == "99" | state == "N" & region_1=="00" , region_2,
ifelse(state == "N" & region_1 != "99" | state == "N" & region_1 != "00", region_1,
ifelse(state == "T", region_1,
ifelse(state == "3", region,
ifelse(state == "W" & region_1 != "ED" | state == "W" & region_1 != "FL" | state == "W" & region_1 != "SG" | state == "W" & region_1 != "SY" | state == "W" & region_1 != "XP" | state == "W" & region_1 != "AL" | state == "W" & region_1 != "AG" | state == "W" & region_1 != "EB" | state == "W" & region_1!= "AB", region_1,
NA))))))
Problem
Output has issue with state == "w" code. It's not recognizing my attempted "IS NOT" and pastes "region_1" instead of NA(see lines 4:7). It's likely the same is happening for state == "N",however, the conditions are not met in the mock data. Looking for a solution.
Aucun commentaire:
Enregistrer un commentaire