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.
>
>Thanks in advance,
>
>
>Jorge
>
> [[alternative HTML version deleted]]
>
>______________________________________________
>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.



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. Received on Fri 11 Apr 2008 - 21:53:13 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Fri 11 Apr 2008 - 22:30:29 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive