Simplytif
Simplytif

Reputation: 51

Add rows filled with NA to complete my data

I want to add rows in order to have 5 rows for each year, filled with NAs.

My data set:

df <- data.frame( a= c(2001,2001,2001,2001,2003,2004,2004,2004,2004,2004),
                  b= c(2,4,5,7,8,6,2,4,2,1))

My desired output:

df2 <- data.frame( a= c(2001,2001,2001,2001,2001,2002,2002,2002,2002,2002,2003,2003,2003,2003,2003,2004,2004,2004,2004,2004),
                  b= c(2,4,5,7,NA,NA,NA,NA,NA,NA,8,NA,NA,NA,NA,6,2,4,2,1) )

EDIT:

Other years that exist on my data has more than 5 values for each year stay the same!

Upvotes: 1

Views: 86

Answers (1)

agstudy
agstudy

Reputation: 121608

A base R solution :

do.call(rbind,
  by(df,df$a,function(x){
    if(nrow(x)<5)  
      rbind(x,data.frame(a=unique(x$a),b=rep(NA,5-nrow(x))))
    else x
  })
)

Upvotes: 1

Related Questions