Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R - Add values to data frame matching a certain criteria

Tags:

dataframe

r

match

I have the following two data frames:

d <- data.frame(c1 = c("A","A","B","C","A","C","D","D"))

map <- data.frame(c1 = c("A","B","C","D"), c2 = c(12,14,16,25))

How can I add another column called "match" to data frame d that contains corresponding values found in data frame map? So data frame d should look like:

A 12
A 12
B 14
C 16
A 12
C 16
D 25
D 25

Many thanks in advance!

like image 797
user969113 Avatar asked Nov 21 '12 11:11

user969113


1 Answers

Using the function called match:

d$match <- map$c2[match(d$c1,map$c1)]

And because of the way these levels are specified, you could also do:

d$match <- map$c2[d$c1]

But this only works if each row in match exactly matches the levels of the c1 factor in order.

like image 104
Sacha Epskamp Avatar answered Nov 15 '22 09:11

Sacha Epskamp