[R] match values from data.frame and vector

peter dalgaard pdalgd at gmail.com
Sun Apr 15 10:12:01 CEST 2012


On Apr 15, 2012, at 09:36 , Omphalodes Verna wrote:

> Dear R helpers!
> 
> I have a vector 'x1' and data.frame 'df1'. Do you have any suggestion how to get vector x2, which will be a result of matching values from vector 'x1' and values from 'df1'? Please, see the example:
> 
> x1 <- c(rep(1,3), rep(NA,2), rep(2,4))
> df1 <- data.frame(c1 = c(1,2), c2 = c(5,6))
> 
> I would like to get vector x2:
>> x2
> [1]  5  5  5 NA NA  6  6  6  6
> 
> Thanks a lot, OV

You mean like this?

> df1$c2[match(x1, df1$c1)]
[1]  5  5  5 NA NA  6  6  6  6


-- 
Peter Dalgaard, Professor,
Center for Statistics, Copenhagen Business School
Solbjerg Plads 3, 2000 Frederiksberg, Denmark
Phone: (+45)38153501
Email: pd.mes at cbs.dk  Priv: PDalgd at gmail.com



More information about the R-help mailing list