简体   繁体   中英

R - Appending column to data frame. Match by year.

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.

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')

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM