0

New to R. Brain size of pea.

Suppose I have two separate data frames.

df1 = tibble(
  date = as.Date(c("1990-10-01", "1991-11-01", "1992-11-01")),
  wage = c(4, 5, 6) 
)

df2 = tibble(
  date = as.Date(c("1990-01-01", "1991-01-01", "1992-01-01")),
  cpi = c(2, 3, 4) 
)

I wish to add a column from the second data frame to the first. Also, I wish to match just the year of the date.

I'm thinking left_join factors in some how, but I am unsure as to exactly how.

ixodid
  • 2,180
  • 1
  • 19
  • 46

2 Answers2

0

dplyr should work for this.

library(dplyr)
library(lubridate)
df1$year<-year(df1$date)
df2$year<-year(df2$date)
df1<-left_join(df1,df2[c('year','cpi')],by='year')
AffableAmbler
  • 377
  • 3
  • 15
0

This should do the trick

# turn dates into years
df1$date <- format(df1$date, "%Y")
df2$date <- format(df2$date, "%Y")

Use base::merge or dplyr::lef_join to combine the two:

merge(df1, df2, all.x = TRUE)
# or
left_join(df1, df2)
Jordi
  • 1,313
  • 8
  • 13
  • 1
    @ixodid Glad it helps. Please consider [accepting](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) whichever of the answers you prefer. – Jordi Mar 07 '18 at 20:30