create multiple data records from a single record

Sorry to keep dragging this out, I keep getting pulled into other projects.

I can run the code and get that same result, but I still have 2 issues:

  • This code produces the table we want, but only for the first 6 rows in the original dataset. How do I generalize it to run on all 9488 rows in the original dataset?

  • When I open up datainit it only shows me the collapsed view of the data. I tried running the code you sent me back in the beginning (included below) to expand datainit to the view that we see in the console, but it gives me an error, 'x' is not a regular sequence.

dput(head(RZD_multi))
(datainit = structure(list(ZipCode = c(37401L, 38231L, 38231L, 37056L, 37056L, 37056L),
                          Plus4Low = c("0102", "0401", "0521", "0001", "0021", "0031"),
                          Plus4High = c("0151", "0520", "0580", "0018", "0028", "0048"),
                          CenLat = c(35.045799, 36.202288, 36.202288, 0, 0, 0), 
                          CenLon = c(-85.306528, -88.420878, -88.420878, 0, 0, 0)),
                     row.names = c(143L, 217L, 218L, 910L, 911L, 912L), class = "data.frame"))

datainit %>% 
  mutate_at(vars(starts_with("Plus")),
            ~as.integer(.)) %>% 
  rowwise() %>%
  mutate(slist = list(Plus4Low:Plus4High)) %>% 
  unnest(slist) %>% 
  mutate(ZipPlus4=str_c(ZipCode, str_pad(slist, 4, "left", "0"), sep=""))

datainit$Plus4Low = as.integer(datainit$Plus4Low)
datainit$Plus4High = as.integer(datainit$Plus4High)
datainit %>%
  pivot_longer(-ZipCode,names_to="TypeSuff",values_to="Suff") %>%
  group_by(ZipCode) %>%
  complete(Suff=full_seq(Suff,1)) %>%
  ungroup() %>%
  mutate(Zip9=str_c(ZipCode,str_pad(Suff,4,"left","0"),sep=""))

Don't use the head funtion in your code. You can start with RZD_multi. We just wanted a few rows on here and didn't need the full dataset. Your code will look like this:

RZD_zipexpand <- RZD_multi %>% 
  mutate_at(vars(starts_with("Plus")),
            ~as.integer(.)) %>% 
  rowwise() %>%
  mutate(slist = list(Plus4Low:Plus4High)) %>% 
  unnest(slist) %>% 
  mutate(ZipPlus4=str_c(ZipCode, str_pad(slist, 4, "left", "0"), sep=""))

where RZD_zipexpand is the data you want.

That is beautiful. Thank you so much for your time, and your patience!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.