0

I am new to R and I'm trying to separate the data I got into a more manageable dataset.

So far, the dataset looks like this

mo  yr  conc.
1  2009 0.6
2  2009 0.8
4  2009 0.3
1  2010 0.5
2  2010 0.6

And I'm trying to get it to a form like this one

mo conc2009 conc2010
1  0.6        0.5
2  0.8        0.6
3  NA         NA
4  0.3        NA

How can I achieve that? I was thinking to use separate, but it doesn't seems like that's its main purpose, any idea?

zx8754
  • 52,746
  • 12
  • 114
  • 209
Raffaello Nardin
  • 151
  • 2
  • 11

1 Answers1

1

We can use complete to create a sequence between maximum and minimum value of mo for each yr and then spread it to wide format.

library(tidyverse)

df %>%
  complete(yr, mo = seq(min(mo), max(mo))) %>%
  mutate(yr = paste0('conc', yr)) %>%
  spread(yr, conc)

#     mo  conc2009 conc2010
#   <int>    <dbl>    <dbl>
#1     1      0.6      0.5
#2     2      0.8      0.6
#3     3      NA       NA  
#4     4      0.3      NA  
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213