[R] merge verctor and matrix

David Winsemius dwinsemius at comcast.net
Wed Sep 22 15:46:35 CEST 2010


On Sep 22, 2010, at 3:57 AM, Yuan Jian wrote:

> hi,
> can anyone tell me how to merge a vector and a matrix?
>> v=c(1,4,2)
>> names(v)=c("e","r","t")
>> m=matrix(c("r","t","r","s","e",5,6,7,8,9),nr=5)
>> colnames(m)=c("c1","c2")
> I want to do like
> merge(v, m, by.x="names",by.y="c1")
> I got error
> Error in fix.by(by.x, x) : 'by' must specify valid column(s)

When v is coerced to a data.frame, its names become row.names:

 > merge(m, v, by.x="c1", by.y="row.names", all=TRUE)
   c1 c2  y
1  e  9  1
2  r  5  4
3  r  7  4
4  s  8 NA
5  t  6  2

 > merge(v, m, by.y="c1", by.x="row.names", all=TRUE)
   Row.names  x c2
1         e  1  9
2         r  4  5
3         r  4  7
4         s NA  8
5         t  2  6

>
> thanks
> jian
>
>
>
>
> 	[[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.

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list