[R] merge for data.frame and matrix

David Winsemius dwinsemius at comcast.net
Thu May 13 15:48:30 CEST 2010


On May 13, 2010, at 5:34 AM, Dennis Murphy wrote:

> Hi:
>
> You've got to convert m to a data frame first:

Well, that would be one way, but it is not true that it is necessary.  
The Details section of the help page for merge says that row,names is  
an acceptable "by" specification, so without the data.frame coercion,  
this is another method:

 > merge(df, m, by.x="col1", by.y="row.names")
   col1 col2.x col1 col2.y
1   kk      6    8      9
2   kk      3    8      9

-- 
David.

>
>> m <- data.frame(m)
>> m$nms <- rownames(m)
>> merge(df, m, by.x = 'col1', by.y = 'row.names')
>  col1 col2.x col1 col2.y
> 1   kk      6    8      9
> 2   kk      3    8      9
>
> HTH,
> Dennis
>
> On Wed, May 12, 2010 at 5:03 PM, Yuan Jian <jayuan2008 at yahoo.com>  
> wrote:
>
>> Hello,
>>
>> how to merge a data.frame and a matrix by one column in the  
>> data.frame and
>> rownames of the matrix?
>> df <- data.frame(col1=c("kk","yy","kk"),col2=c(6,4,3))
>>> df
>>  col1 col2
>> 1   kk    6
>> 2   yy    4
>> 3   kk    3
>> m<-matrix(c(3,8,56,9), nrow=2, dimnames =
>> list(c("aa","kk"),c("col1","col2")))
>>> m
>>   col1 col2
>> aa    3   56
>> kk    8    9
>>
>> the result is expected as
>> col1.x col2.x col1.y col2.y
>> kk       6        8        9
>> kk       3        8        9
>>
>> Yuan 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.
>>
>>
>
> 	[[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