Thank you so much to Mark and Gabor for their codes (please see below). Now
I solved my problem : )
Best,
Jorge
# --------- Mark's code
res=sapply(colnames(dx), function(.colname) {
if (.colname %in% colnames(dy)) dy[,.colname]
else {numeric(nrow(dy))}
})
res
# --------- Gabor's code
res=as.matrix(replace(as.data.frame(0 * dx), colnames(dy), dy))
# If dx were a data frame already we could eliminate as.data.frame
# and as.matrix so it would reduce to, in that case:
res=replace(0 * dx, colnames(dy), dy)) # only if dx is data.frame
> On Fri, Apr 11, 2008 at 5:36 PM, Jorge Velez
> wrote:
> > 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.
> >
> > Thanks in advance,
> >
> >
> > Jorge
> >
> > [[alternative HTML version deleted]]
> >
> > ______________________________________________
> > R-help@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.
> >
>
[[alternative HTML version deleted]]