shanunderwood
shanunderwood

Reputation: 7

How to perform a VLOOKUP in R?

I am replicating a CSV file in R (originally created in excel), that is compiled using various data sources. When i made this CSV in excel i used a vlookup to populate certain columns based on another data source/other spreadsheet.

How can i populate a column in R using something similar to a VLOOKUP? i.e. looking for a variable in an external source and matching it with another column in the df?

For example, the formula in the excel version is = =VLOOKUP('[Spreadsheet1]Tab1'!A22,'[Spreadsheet2]Tab2'!$A$6:$B$500,2,FALSE)

How can i make this same formula in R code?

Upvotes: 1

Views: 1668

Answers (1)

dmca
dmca

Reputation: 685

dplyr::left_join() should do the trick:

myData <- data.frame(
  x = c('a', 'b', 'b', 'c')
)

lookUpData <- data.frame(
  key = c('a', 'b', 'c'),
  value = c(1, 2, 3)
)

library(dplyr)

myData %>%
  left_join(lookUpData, by = c(x = 'key')) %>%
  rename(newCol = value)


  x newCol
1 a      1
2 b      2
3 b      2
4 c      3

Upvotes: 1

Related Questions