JustCurious JustCurious - 3 months ago 10
R Question

How to add column to data frame using another data frame?

I have two data frames as given below.

> df1 = data.frame(Letters1 = as.factor(rep(letters[1:3],c(4,3,5))), Numbers = 1:12)
> df1
Letters1 Numbers
1 a 1
2 a 2
3 a 3
4 a 4
5 b 5
6 b 6
7 b 7
8 c 8
9 c 9
10 c 10
11 c 11
12 c 12
> df2 = data.frame(Letters2 = letters[1:3],Dates = as.Date(1:3, origin = "2016-07-31"))
> df2
Letters2 Dates
1 a 2016-08-01
2 b 2016-08-02
3 c 2016-08-03


How to add Dates column from data frame 2 to data frame 1 for each character of Letters1 column?

Answer

Will this help?

df1$Dates <- df2$Dates[match(df1$Letters1, df2$Letters2)]