Sunday, April 18, 2010

Extract rows from data frame based on row names from anotherdata frame

Found in google searches .. can be useful

#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

# continuing with 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)]

No comments: