[R] add column with values found in another data frame

Pete Brecknock Peter.Brecknock at bp.com
Sun Jan 15 05:58:01 CET 2012


jdog76 wrote
> 
> I am positive this problem has a very simple solution, but I have been
> unable to find it, so I am asking for your help. I need to know how to
> look something up in one data frame and add it as a column in another.  If
> I have a data frame that looks like this:
> 
>> frame1
>   ID  score  test age
> 1  Guy1 10 1  20
> 2 Guy1 13 2  20
> 3 Guy2 9 1  33
> 4 Guy2 11 2  33
> 
> and another frame that looks like this:
> 
>> frame2
>   ID
> 1 Guy1
> 2 Guy2
> 
> How do I add a column to frame2 so it looks like this:
> 
>   ID age
> 1 Guy1 20
> 2 Guy2 33
> 
> I know this must be simple, but I couldn't find the solution by searching.
> 
> thanks so much
> Jeremy
> 

How about ....

frame2$age = frame1[match(frame2$ID, frame1$ID),"age"]

print(frame2)
    ID age
1 Guy1  20
2 Guy2  33

HTH

Pete



--
View this message in context: http://r.789695.n4.nabble.com/add-column-with-values-found-in-another-data-frame-tp4295626p4296307.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list