Reputation: 845
I have two data frames. The data frames are different lengths, but have the same IDs in their ID columns. I would like to create a column in df
called Classification
based on the Classification
in df2
. I would like the Classification
column in the df
to match up with the appropriate ID
listed in df2
. Is there a good way to do this?
#Example data set
library(lubridate)
date <- rep_len(seq(dmy("26-12-2010"), dmy("20-12-2011"), by = "days"), 500)
ID <- rep(seq(1, 5), 100)
ID2 <- rep(seq(1,5), 1)
Classification2 <- c("A", "B", "C", "D", "E")
df <- data.frame(date = date,
x = runif(length(date), min = 60000, max = 80000),
y = runif(length(date), min = 800000, max = 900000),
ID)
df2 <- data.frame(ID2, Classification)
Upvotes: 0
Views: 864
Reputation: 655
A dplyr
solution using left_join()
.
left_join(df, df2, c("ID" = "ID2"))
Upvotes: 1
Reputation: 365
Are you looking for a merge between df and df2? Assuming Classification is a column in df.
df2 <- merge(df2, df, by.x = "ID2", by.y = "ID", all.x = TRUE)
Upvotes: 0