Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use merge so that I have data for all times?

Tags:

merge

r

I'm trying to change a data into which all entities have value for all possible times(months). Here's what I'm trying;

Class  Value  month
  A      10     1
  A      12     3
  A      9      12
  B      11     1
  B      10     8

From the data above, I want to get the following data;

Class  Value  month
  A      10     1
  A      NA     2
  A      12     3
  A      NA     4
        ....
  A      9      12
  B      11     1
  B      NA     2
        ....
  B      10     8
  B      NA     9
        ....
  B      NA     12

So I want to have all possible cells with through month from 1 to 12; How can I do this? I'm right now trying it with merge function, but appreciate any other ways to approach.

like image 625
Mons2us Avatar asked Feb 04 '23 16:02

Mons2us


1 Answers

We can use tidyverse

library(tidyverse)
df1 %>%
   complete(Class, month = min(month):max(month)) %>% 
   select_(.dots = names(df1)) %>%  #if we need to be in the same column order
   as.data.frame() #if needed to convert to 'data.frame'
like image 80
akrun Avatar answered Feb 07 '23 06:02

akrun