Merge extra column into an R data.frame

Small tip that I keep forgetting and then can't remember the name of the function again.

Say you have a vector you want to merge into a data.frame, or you want to merge just the one column from a data.frame, using merge() can be a bit cumbersome, and ordering of the original data.frame isn't preserved.

Instead you can use match():

>     data <- data.frame(
+         person = c('george', 'edwina', 'carol', 'edwina'),
+         day = c(1,2,3,4),
+         stringsAsFactors = FALSE)
>     ages <- c(carol = 40, edwina = 33, george = 8)
>     data$ages <- ages[match(data$person, names(ages))]
> data
  person day ages
1 george   1    8
2 edwina   2   33
3  carol   3   40
4 edwina   4   33

> more <- data.frame(
    person = c('carol', 'edwina', 'george'),
    surname = c('roberts', 'smith', 'baker'),
    stringsAsFactors = FALSE)
> data$surname <- more[match(data$person, more$person), 'surname']
> data
  person day ages surname
  1 george   1    8   baker
  2 edwina   2   33   smith
  3  carol   3   40 roberts
  4 edwina   4   33   smith