[R] How to select rows with identical index from two matrix?
Henrik Bengtsson
hb at stat.berkeley.edu
Wed Nov 21 09:23:57 CET 2007
On Nov 20, 2007 7:04 PM, Moshe Olshansky <m_olshansky at yahoo.com> wrote:
> You can do the following:
>
> set1 <- Matrix1[,1]
> set2 <- Matrix2[,1]
> common <- intersect(set1,set2)
> ind1 <- which(set1 %in% common)
> ind2 <- which(set2 %in% common)
>
> A1 <- Matrix1[ind1,-1]
> A2 <- Matrix2[ind2,-1]
Ok, this far.
>
> and if you wish,
>
> rownames(A1) <- common
> rownames(A2) <- common
The latter two are not guaranteed to be correct, because they assume
that 'ind1' and 'ind2' also reorders the rows according to 'common',
but this far you only used set operations. Try with:
Matrix1 <- matrix(letters[1:5], nrow=5, ncol=2)
Matrix2 <- matrix(letters[5:1], nrow=5, ncol=2)
This is best understood if you remove the which():es and just keep the
logical vectors. Instead, match() will order the indices according to
the target vector. Make sure to deal with missing values. Example:
idx1 <- na.omit(match(set1, common))
idx2 <- na.omit(match(set2, common))
/H
>
>
> --- "C.S. Liu" <qnerv at stat.sinica.edu.tw> wrote:
>
> > Dear list,
> >
> > I have two martix like these, each rows with
> > name in the matrix.
> >
> > I try to select rows with identical name from
> > two matrix and calculate their correlation.
> >
> > Matrix1:
> > 2-Sep 9 5.5 1 7.18 10.0 8
> > 139.45
> > 2-Sep 7 4.9 15 8.22 61.68 9
> > 123.62
> > 4-Sep
> > 5-Sep
> > AAMP
> > A2M
> > A2M
> > .
> > .
> > .
> >
> > Matrix2:
> >
> > 2-Sep 4 7 1 6.8 12 8 19.4
> > 2-Sep 2 8 15 2.2 6.8 12 13.2
> > 4-Sep
> > AAMP
> > AAMP
> > ABCA5
> > A2M
> > A2M
> >
> > I try to select rows with identical name from two
> > matrix and calculate their correlation.
> >
> > However, I got trouble when loading these two matrix
> > into R as header=TRUE.
> >
> > So I use header=FLASE and these name become
> > character in the first column.
> >
> > How do I extract the first column of matrix 1 and
> > compare to the first column of matrix 2?
> >
> > And if they are identical I compute their
> > correlation?
> >
> >
> > SIncerely yours,
> > Chiahsin Liu
> >
> > [[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.
>
More information about the R-help
mailing list