0

I am trying to use spread as part of the tidyr package. I have one key column (structure_type) and four value columns. (structure_type contains three factor levels.) All the documentation I've seen assumes that spread can only be used for one key column and one value column. But it seems like this should be possible to do this. Perhaps I should use the reshape library instead?

This answer came close but I couldn't reproduce it.

library(tidycensus)
library(tidyr)
units_str_puma <- get_acs(geography = 'public use microdata area', table = "B25024",
                     state = c('OR', 'WA'))
units_str2_puma <- units_str_puma %>%
  mutate(structure_type = case_when(variable == "B25024_001" ~ "Total units",
                                    variable %in% c("B25024_002", "B25024_003") ~ "One-unit structure",
                                    TRUE ~ "Other")) %>%
  group_by(structure_type, GEOID) %>%
  summarize(units = sum(estimate),
            units_moe = moe_sum(moe = moe, estimate = estimate),
            units_cv = units_moe/1.645/units,
            units_cv_flag = case_when(units_cv > 0.4 ~ 1,
                                      TRUE ~ 0)) %>%
  spread(key=structure_type, value=c(units, units_moe, units_cv, units_cv_flag), drop=FALSE)

Data structure

oatmilkyway
  • 429
  • 1
  • 6
  • 17
  • 1
    Can you post some data in copy-and-pastaeble format? It appears that I'd need to sign up to access the data in your example. – Dan Dec 06 '18 at 18:35
  • 4
    I'm confused. (1) Please do not post an image of code/data/errors: it cannot be copied or searched (SEO), it breaks screen-readers, and it may not fit well on some mobile devices. Ref: https://meta.stackoverflow.com/a/285557/3358272. (2) Please provide clear sample data for us to use, one example is `dput(head(x))` with just-enough variability to get your point across, other examples at https://stackoverflow.com/questions/5963269. (3) Please provide clear expected output. Logically, I do not know what `spread`ing this type of data should look like post-expansion. – r2evans Dec 06 '18 at 18:36
  • There are `data.table` and `reshape` options that might help - https://stackoverflow.com/questions/11608167/reshape-multiple-value-columns-to-wide-format – Mike Dec 06 '18 at 18:54

0 Answers0