[R] Extract rows from data frame based on row names from anotherdata frame

David Winsemius dwinsemius at comcast.net
Sat Dec 13 15:50:39 CET 2008


Matching row names was the request.

# continuing with your example:

  rownames(d1)<- letters[1:5]
  rownames(d2)<- letters[3:7]

# and then for rownames of d1 that are also in rownames of d2:
# for the full rows ...

d1[row.names(d1) %in% row.names(d2),]

# or for just the names:

rownames(d1)[row.names(d1) %in% row.names(d2)]

--  
David Winsemius

On Dec 11, 2008, at 4:21 PM, Daniel Malter wrote:

> Hi
>
> #Create data and data frames
> x=rnorm(5,0,1)
> y=rnorm(5,0,1)
> z=rnorm(5,0,1)
> d1=data.frame(x,y)
> d2=data.frame(y,z)
>
> #which variable name in d2 is a variable name in d1?
> names(d2[names(d2)%in%names(d1)]) # it's y
>
> #give me the columns of d2 that have variable names
> #that are also variable names in d1
>
> d2[names(d2)==names(d2[names(d2)%in%names(d1)])]
>
> #check
> d2$y
>
> Cheers,
> Daniel
>
>
> -------------------------
> cuncta stricte discussurus
> -------------------------
>
> -----Ursprüngliche Nachricht-----
> Von: r-help-bounces at r-project.org [mailto:r-help-bounces at r- 
> project.org] Im
> Auftrag von Wade Wall
> Gesendet: Thursday, December 11, 2008 3:59 PM
> An: r-help at stat.math.ethz.ch
> Betreff: [R] Extract rows from data frame based on row names from
> anotherdata frame
>
> Hi all,
>
> Is there a function to extract row names from a data frame based on  
> row
> names from another data frame?  I can write a loop function to do  
> this, but
> this may be inefficient in terms of processing.
>
> thanks for any information,
>
> Wade
>
> ______________________________________________
> 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