[R] Add columns of dataset

Phil Spector spector at stat.berkeley.edu
Fri Dec 3 21:52:46 CET 2010


Lisa -
    I think something like this will do what you want:

> mydf = data.frame(id=1:3,var1=c(0,.4,0),var2=c(.1,.6,0),var4=c(.3,0,0),var7=c(.9,0,.8),var8=c(0,.2,.7))
> allvars = c('id',paste('var',1:8,sep=''))
> mydf[,allvars[!allvars %in% names(mydf)]] = 0
> mydf = mydf[,sort(names(mydf))]
> mydf
   id var1 var2 var3 var4 var5 var6 var7 var8
1  1  0.0  0.1    0  0.3    0    0  0.9  0.0
2  2  0.4  0.6    0  0.0    0    0  0.0  0.2
3  3  0.0  0.0    0  0.0    0    0  0.8  0.7

 					- Phil Spector
 					 Statistical Computing Facility
 					 Department of Statistics
 					 UC Berkeley
 					 spector at stat.berkeley.edu




On Fri, 3 Dec 2010, Lisa wrote:

>
> Dear all,
>
> I have a dataset that looks like
>
> id  var1  var2  var4  var7  var8
> 1    0.0   0.1    0.3    0.9    0.0
> 2    0.4   0.6    0.0    0.0    0.2
> 3    0.0   0.0    0.0    0.8    0.7
>
> Some columns are missed, for example, here the fourth (var3), sixth(var5)
> and seventh (var6) columns. I want to first determine which columns are
> missed in a huge dataset and then add the missed columns with the values of
> zeros that looks like
>
> id  var1  var2   var3  var4  var5  var6  var7  var8
> 1    0.0   0.1     0.0    0.3   0.0    0.0   0.9    0.0
> 2    0.4   0.6     0.0    0.0   0.0    0.0   0.0    0.2
> 3    0.0   0.0     0.0    0.0   0.0    0.0   0.8    0.7
>
> Can anybody please help how to get this done? Thanks a lot in advance
>
> Lisa
>
> -- 
> View this message in context: http://r.789695.n4.nabble.com/Add-columns-of-dataset-tp3071722p3071722.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



More information about the R-help mailing list