Reputation: 446
Suppose I have two data frames such as:
df1 <- data.frame(Date=seq.Date(as.Date("2019-02-01"),as.Date("2019-02-28"), by="days"),
Coyote=(rep(10,28)))
df2 <- data.frame(Date=seq.Date(as.Date("2019-01-01"),as.Date("2019-03-31"), by="days"),
Birds=(rep(2,90)))
How can I merge the two Date
s column in df1
without affecting the other variables?
Outcome desired:
df_desired <- data.frame(Date=seq.Date(as.Date("2019-01-01"),as.Date("2019-03-31"), by="days"),
Coyote=c(rep(NA,31),rep(10,28),rep(NA,31)))
Date Coyote
1 2019-01-01 NA
...
31 2019-01-31 NA
32 2019-02-01 10
...
59 2019-02-28 10
60 2019-03-01 NA
...
90 2019-03-31 NA
Upvotes: 0
Views: 58
Reputation: 160407
Do you mean something like this? (Just a sampling, the real results are 90 rows.)
out <- merge(df1, df2[,"Date",drop=FALSE], by="Date", all=TRUE)
### and a sampling of the results, ordered
out[order(out$Date),][c(1:3, 37:39, 88:90),]
# Date Coyote
# 1 2019-01-01 NA
# 2 2019-01-02 NA
# 3 2019-01-03 NA
# 37 2019-02-06 10
# 38 2019-02-07 10
# 39 2019-02-08 10
# 88 2019-03-29 NA
# 89 2019-03-30 NA
# 90 2019-03-31 NA
Upvotes: 3