Hi all, I have more than two files and merge by a single column and preserve the other columns. Here is an example of two files dat1 <- read.table(header=TRUE, text=' ID T1 T2 ID1 125 245 ID2 141 264 ID3 133 281') dat2 <- read.table(header=TRUE, text=' ID G1 G2 ID2 25 46 ID4 41 64 ID5 33 81') How do I get the following output? ID T1 T2 G1 G2 ID1 125 245 0 0 ID2 141 264 25 46 ID3 133 281 0 0 ID4 0 0 41 64 ID5 0 0 33 81 Thank you. [[alternative HTML version deleted]]
Initially: dat3 <- merge(dat1, dat2, all.x = TRUE, all.y = TRUE) ... and then you had asked for 0, not NA in your results. I think that's not a good idea - since you can't distinguish a legitimate value 0 from a missing value that way, but if you must: dat3[is.na(dat3)] <- 0 B. (and don't post in HTML)> On Mar 26, 2017, at 12:37 AM, Ashta <sewashm at gmail.com> wrote: > > Hi all, > > I have more than two files and merge by a single column and preserve the > other columns. > Here is an example of two files > > dat1 <- read.table(header=TRUE, text=' ID T1 T2 > ID1 125 245 > ID2 141 264 > ID3 133 281') > > dat2 <- read.table(header=TRUE, text=' ID G1 G2 > ID2 25 46 > ID4 41 64 > ID5 33 81') > > How do I get the following output? > > ID T1 T2 G1 G2 > ID1 125 245 0 0 > ID2 141 264 25 46 > ID3 133 281 0 0 > ID4 0 0 41 64 > ID5 0 0 33 81 > > Thank you. > > [[alternative HTML version deleted]] > > ______________________________________________ > R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see > 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.
?merge with all.x and all.y both set to TRUE. Use the NA's **NOT** 0's for nonmatching values that merge() gives. Cheers, Bert Bert Gunter "The trouble with having an open mind is that people keep coming along and sticking things into it." -- Opus (aka Berkeley Breathed in his "Bloom County" comic strip ) On Sat, Mar 25, 2017 at 9:37 PM, Ashta <sewashm at gmail.com> wrote:> Hi all, > > I have more than two files and merge by a single column and preserve the > other columns. > Here is an example of two files > > dat1 <- read.table(header=TRUE, text=' ID T1 T2 > ID1 125 245 > ID2 141 264 > ID3 133 281') > > dat2 <- read.table(header=TRUE, text=' ID G1 G2 > ID2 25 46 > ID4 41 64 > ID5 33 81') > > How do I get the following output? > > ID T1 T2 G1 G2 > ID1 125 245 0 0 > ID2 141 264 25 46 > ID3 133 281 0 0 > ID4 0 0 41 64 > ID5 0 0 33 81 > > Thank you. > > [[alternative HTML version deleted]] > > ______________________________________________ > R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see > 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.