# Re: [R] How to fill out some columns?

From: <markleeds_at_verizon.net>
Date: Fri, 11 Apr 2008 16:49:33 -0500 (CDT)

>From: Jorge Velez <jorgeivanvelez_at_gmail.com>
>Date: 2008/04/11 Fri PM 04:36:58 CDT
>To: R <r-help_at_r-project.org>
>Subject: [R] How to fill out some columns?

below works but my guess is that there's a better way.

set.seed(4)
dx=matrix(rnorm(6*5),ncol=6)
colnames(dx)=LETTERS[1:6]

dy=matrix(rnorm(3*5),ncol=3)
colnames(dy)=c('A','C','E')

sapply(colnames(dx), function(.colname) {   if ( .colname %in% colnames(dy) ) {
return(dy[,.colname])
} else {
return(numeric(nrow(dy)))
}
})

>Dear R users,
>
>I'm working with 2 data sets which look like (for example) dx and dy in the
>next code:
>
># Seed
>set.seed(4)
>
># First data frame
>dx=matrix(rnorm(6*5),ncol=6)
>colnames(dx)=LETTERS[1:6]
>
># Second data frame
>dy=matrix(rnorm(3*5),ncol=3)
>colnames(dy)=c('A','C','E')
>
>
>As you will notice, some columns in both data sets have the same names. At
>the end, what I need is something like:
>
>
>> res
> A B C D E F
>[1,] 0.1534642 0 -0.4045198 0 1.3437086 0
>[2,] 1.0519326 0 -0.2274054 0 0.1815354 0
>[3,] -0.7542112 0 0.9340962 0 1.2925123 0
>[4,] -1.4821891 0 -0.4658959 0 -1.6880486 0
>[5,] 0.8611319 0 -0.6375435 0 -0.8209936 0
>
>
>where columns "A", "C" and "E" are the dy columns and columns "B" and "D"
>are zeros because, when we compare dx and dy, they are not present. Any
>suggestion would be greatly appreciated.
>
>
>
>Jorge
>
> [[alternative HTML version deleted]]
>
>______________________________________________
>R-help_at_r-project.org mailing list
>https://stat.ethz.ch/mailman/listinfo/r-help