年度数据(复制12次):
firm date1 x 1 2000 5 1 2000 5 1 2000 5 1 2000 5 1 2000 5 1 2000 5 1 2000 5 1 2000 5 1 2000 5 1 2000 5 1 2000 5 1 2000 5
每月数据:
firm date2 y 1 200001 3 1 200002 7 1 200003 2 1 200004 8 1 200005 9 1 200006 3 1 200007 6 1 200008 2 1 200009 7 1 200010 2 1 200011 3 1 200012 8
如何将年度数据与有6个月延迟的月度数据合并(将第一个月的年度数据与200007的月度数据合并,将第二个月的年度数据合并为200008的月度数据)?
预期成果:
firm date1 date2 x y 1 2000 200007 1 2000 200008 1 2000 200009 1 2000 200010 1 2000 200011 1 2000 200012 1 2000 200101 1 2000 200102 1 2000 200103 1 2000 200104 1 2000 200105 1 2000 200106 1 2001 200107
发布于 2018-02-14 17:02:51
试试这个:
year<-data.frame("firm"=c(1,1,1,1), date1=c(2000,2000,2000,2000),x=c(5,5,5,5)) #Yearly dn
month<-data.frame("firm"=c(1,1,1,1), date2=c(200001,200002,200003,200004),y=c(3,7,2,8)) #Monthly db
month$date1<-substr(month$date2,1,4) #Create a common key between two dataframes
merge(year[!duplicated(year),],month,by.x="date1",by.y="date1",all.x=T)
date1 firm.x x firm.y date2 y
1 2000 1 5 1 200001 3
2 2000 1 5 1 200002 7
3 2000 1 5 1 200003 2
4 2000 1 5 1 200004 8发布于 2018-02-14 17:03:35
将另一列以正确的日期格式添加到第一个dataframe中可能是个好主意。这里有一个tidyverse解决方案:
library(dplyr)
library(lubridate)
df <- df %>%
mutate(new_date = date1*10000 + row_number()*100 + 1,
new_date = ymd(new_date),
join_date = new_date + months(6),
join_date = year(join_date)*100 + month(join_date))然后,您将希望使用join_date和date2合并这两个数据格式
https://stackoverflow.com/questions/48791929
复制相似问题