I need to generate column zip3 out of zip1 and zip2. zip2 is the first 5 characters of zip1.
To generate zip3 if zip2 did NOT exist in the entire zip1 column then zip1 value will be chosen otherwise zip2 will be chosen.
How can I do this easily without a loop? I tried this, but I cannot apply it to the entire DF
df <- structure(list(zip1 = c("12345-1234", "12345", "55555", "11111",
"22222-1234", "55555-1234", "11111", "66666-1234"), zip2 = c(12345L,
12345L, 55555L, 11111L, 22222L, 55555L, 11111L, 66666L), zip3 = c("12345",
"12345", "55555", "11111", "22222-1234", "55555", "11111", "66666-1234"
)), class = "data.frame", row.names = c(NA, -8L))
library(dplyr)
df <- df %>% mutate(zip3=if_else(sum(df$zip1==zip2)>0,zip2,zip1))
