You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R中合并不同日期的DataFrame,保留双方条目并填充NA?

Solution to Merge DataFrames with Full Date Coverage

Got it, let's fix this for you! The issue is that left_join() only retains all rows from your first DataFrame (df1) and matches what it can from the second (df2). To keep every date from both DataFrames and fill missing entries with NA, you need a full outer join using full_join() instead.

Step-by-Step Adjusted Code

First, we'll rename the seq columns to seq1 and seq2 for clarity, then use full_join() to combine both datasets:

library(lubridate)
library(dplyr)

# Create df1: Last day of each month
dates_df1 <- seq(as.Date("2019-01-01"), floor_date(Sys.Date(), "month"), "months") - 1
df1 <- tibble(dates = dates_df1, seq1 = rep(1, length(dates_df1)))

# Create df2: Second last day of each month
dates_df2 <- seq(as.Date("2019-01-01"), floor_date(Sys.Date(), "month"), "months") - 2
df2 <- tibble(dates = dates_df2, seq2 = rep(2, length(dates_df2)))

# Perform full outer join to preserve all dates from both dataframes
merged_df <- full_join(df1, df2, by = "dates")

What This Does

  • full_join() keeps every date present in either df1 or df2
  • seq1 will show 1 for dates from df1, and NA for dates only in df2
  • seq2 will show 2 for dates from df2, and NA for dates only in df1

Example Output

Your merged DataFrame will start with exactly the rows you expected:

dates seq1 seq2
1 2018-12-31    1   NA
2 2018-12-30   NA    2
3 2019-01-31    1   NA
4 2019-01-30   NA    2
...

This approach ensures no dates are dropped, and missing values are filled with NA as required.

内容的提问来源于stack exchange,提问作者Michael

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 11:07:33