I have data which looks like this:
Linking <- data.frame(
ID = c(round((runif(20, min=10000, max=99999)), digits=0), rep(NA,10)),
PSU = c(paste("A", round((runif(20, min=10000, max=99999)), digits = 0), sep = ''), rep(NA,10)),
qtr = c(rep(1:10, 2), rep(NA,10)),
date = rep("13/04/56", 30),
Direct = rep(c('D','M','U','U','M'), 6),
stringsAsFactors = F)
Linking$Key <- paste(Linking$ID, Linking$PSU, Linking$qtr, sep='_')
Linking$Key[c(21:30)] <- c("87654_A15467_1", "45623_A23456_2", "67891_A12345_4", "65346_A23987_7",
"E3456782_A456321_6", "E3421986_A34564_8", "E9859873_A123456_9", "E3452_A12345_6", "R765498765_A455634_2", "54678_A12345_5")
I want to extract the separate portions of the "Key" variable, to populate ID, PSU, and qtr, where these values are NA.
I can use this code:
test <- filter(Linking, is.na(ID)) %>%
select(Key)
test2 <- data.frame(do.call(rbind, strsplit(test$Key, "_")), test$Key)
names(test2) <- c("ID", "PSU", "qtr", "Key")
To extract the information which I need for the ID, PSU, and qtr where there are NA values. But how do I add this back in to the original dataset 'Linking'? Merge won't work, because I'll end up with two values for PSU, ID, and qtr (N and the real value)
I asked a similar question here Populate the NA values in a variable with values from a different variables in R , but this question includes variable length values, and includes a more complete dataset, with variables not just related to the 'Key'. Thanks.