如何在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 eitherdf1ordf2seq1will show1for dates fromdf1, andNAfor dates only indf2seq2will show2for dates fromdf2, andNAfor dates only indf1
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
相关产品推荐
相关产品推荐

