0

I have been having a problem with two data frames that I want to merge. One is larger than the other but they share common column names and rownames.

What I would like to do is merge both of them by their specific elements in each row and column.

For example I have 1 data frame: row.names-US Bond,US Stock,EU Bond,EU Stock,Asia Bond,Asia Stock,col.names-Price Risk,Credit Risk,Market Risk;

The other data frame: row.names-US Bond,US Stock;col.names-Price Risk;

Ideally, I would like to merge both data sets by their unique row name and column name.

Sample:

dat1<-matrix(' ',nrow=4,ncol=6)
colnames(dat1)<-c("Value","Percentage","Credit.Risk","Interest.Risk","Interest.Credit.Risk","Total")
rownames(dat1)<-c("Low.Gov.Debt","Low.Corp.Debt","High.Gov.Debt","High.Corp.Debt")
new<-portfolio
rownames(new)<-c("High.Gov.Debt","Low.Gov.Debt")
colnames(new)<-c("Value")
  • Welcome to Stack Overflow! You would make ik a lot easier for others to help you, if you provide [a reproducable example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) – Jaap Mar 11 '14 at 09:07
  • start with `?merge`, if that doesn't answer your question, give us a `dput` of some of the data – JeremyS Mar 11 '14 at 09:19
  • I have already tried merge and plyr and it doesn't work. It just mixes the data in a very uncovential way. – starter123 Mar 11 '14 at 09:33

1 Answers1

1

You need to specify that you're matching by row.names

merge(d1,d2,by="row.names")
Troy
  • 8,581
  • 29
  • 32
  • Merge doesn't work if the data frames are of different size. Also I don't just want them to combine by row name but also by column name so that the each specific element is in its correct position. I tried using library(plyr) and the do.call(rbind...) function but for some reason the data frames won't merge. – starter123 Mar 11 '14 at 12:33
  • how do you want to combine them? append columns, add rows, add values together? merge definitely does work for different sizes data.frames, but will only give the rows that intersect both data.frames (unless you tell it otherwise). Maybe provide some sample data? – Troy Mar 11 '14 at 12:38
  • dat1<-matrix(' ',nrow=4,ncol=6) colnames(dat1)<-c("Value","Percentage","Credit.Risk","Interest.Risk","Interest.Credit.Risk","Total") rownames(dat1)<-c("Low.Gov.Debt","Low.Corp.Debt","High.Gov.Debt","High.Corp.Debt") new<-portfolio rownames(new)<-c("High.Gov.Debt","Low.Gov.Debt") colnames(new)<-c("Value") – starter123 Mar 11 '14 at 13:30
  • just posted a sample code. I basically want to combine dat1 with new given the specific row name and value. – starter123 Mar 11 '14 at 13:31