On 26 Oct 2004 at 15:46, Federico Gherardini wrote:> Hi all, > > Simple and direct question.... > Is it possible to add a shorter column to a data frame or matrix in > such a way that the missing values are replaced with NAs? For example > suppose I have > > 3 2 > 4 2 > 5 8 > > and I want to add a column > > 3 > 3 > > to get... > > 3 2 3 > 4 2 3 > 5 8 NAHi Maybe there is another approach but this shall work no.r <- nrow(df) l.v <- length(your.short.vector) difer <- no.r-l.v cbind(df,c(your.short.vector,rep(NA,difer))) Cheers Petr> > Thanks > > Federico > > ______________________________________________ > R-help at stat.math.ethz.ch mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide! > http://www.R-project.org/posting-guide.htmlPetr Pikal petr.pikal at precheza.cz
Hi, you can use this simple function: add.col<-function(df, new.col) {n.row<-dim(df)[1] length(new.col)<-n.row cbind(df, new.col) } see this example:> x<-cbind(c(1,2,3),c(4,5,6)) > x[,1] [,2] [1,] 1 4 [2,] 2 5 [3,] 3 6> y<-c(7,8) > y[1] 7 8> add.col<-function(df, new.col) {n.row<-dim(df)[1]+ length(new.col)<-n.row + cbind(df, new.col) + + }> > new.df<-add.col(x,y) > new.dfnew.col [1,] 1 4 7 [2,] 2 5 8 [3,] 3 6 NA I hope I help a little. Best Vito you wrote: Hi all, Simple and direct question.... Is it possible to add a shorter column to a data frame or matrix in such a way that the missing values are replaced with NAs? For example suppose I have 3 2 4 2 5 8 and I want to add a column 3 3 to get... 3 2 3 4 2 3 5 8 NA Thanks Federico ====Diventare costruttori di soluzioni "The business of the statistician is to catalyze the scientific learning process." George E. P. Box Visitate il portale http://www.modugno.it/ e in particolare la sezione su Palese http://www.modugno.it/archivio/cat_palese.shtml
In R all things are possible: rcb <- function (...) { # rcb <--> ``ragged cbind'' xxx <- list(...) n <- max(unlist(lapply(xxx,function(x){ifelse(is.matrix(x),nrow(x), length(x))}))) yyy <- lapply(xxx,function(x,n){if(is.matrix(x)) rbind(x,matrix(NA,ncol=ncol(x),nrow=n)) else c(x,rep(NA,n-length(x)))},n=n) do.call("cbind",yyy) } cheers, Rolf Turner rolf at math.unb.ca Federico Gherardini wrote:> Simple and direct question.... Is it possible to add a shorter > column to a data frame or matrix in such a way that the missing > values are replaced with NAs? For example suppose I have > > 3 2 > 4 2 > 5 8 > > and I want to add a column > > 3 > 3 > > to get... > > 3 2 3 > 4 2 3 > 5 8 NA > > Thanks > > Federico
Hi all, Simple and direct question.... Is it possible to add a shorter column to a data frame or matrix in such a way that the missing values are replaced with NAs? For example suppose I have 3 2 4 2 5 8 and I want to add a column 3 3 to get... 3 2 3 4 2 3 5 8 NA Thanks Federico