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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With