Skip to content

Instantly share code, notes, and snippets.

@mhweber
Last active October 1, 2015 19:10
Show Gist options
  • Save mhweber/8672fce88c75f6f56d27 to your computer and use it in GitHub Desktop.
Save mhweber/8672fce88c75f6f56d27 to your computer and use it in GitHub Desktop.
This code takes a lookup table and applies it to a data frame, updating only values for records that occur in the lookup table using indexing and match
# Create data frame 1
x = c("ID1","ID2","ID3","ID4","ID5")
y = c("C1","C2","C3","C4","C5")
d1 = data.frame("SiteID" = x, "Value" = y)
d1
# Create lookup table
x = c("ID2","ID5")
y = c("C5","C2")
lookup = data.frame("SiteID" = x, "Value" = y)
lookup
# Now update the values in data frame just for SiteIDs in the lookup table
d1$Value[d1$SiteID %in% lookup$SiteID] =
lookup$Value[match(d1$SiteID[d1$SiteID %in% lookup$SiteID],lookup$SiteID)]
d1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment