Home > Enterprise >  How to prevent NA of dates when using rbind?
How to prevent NA of dates when using rbind?

Time:12-21

I essentially have two df's that I'd like to bind w/o merging by column. I bind them so that the updated df can follow below the previous one. Everything works find except that the date formats are different, trying to adjust gives me NA values.

Not sure if there's another way to change formats. Any suggestions?

Reprex

# 1
rating <- 1:4
date <- c('2021-12-19', '2021-12-20', '2021-12-21', '2021-12-22')
name <- c('ABC', 'DEF', 'GHI', 'JKL')
title <- c('Manager', 'Accountant','QA','IT')
df1 <- data.frame(rating,date,name,title)
print(df1)

# 2
rating <- 1:4
date <- c('12/15/22', '12/16/22', '12/17/22', '12/18/22')
name <- c('MNO', 'PQR', 'STU', 'VWX')
title <- c('Cyber', 'Broker','D&T','IT')
df2 <- data.frame(rating,date,name,title)
print(df2)

df1$date <- as.Date(df1$date, format = "%d-%m-%y")
df2$date <- as.Date(df2$date, format = "%d-%m-%y")
both <- rbind(df1,df2)

print(both)
  rating date name      title
1      1 <NA>  ABC    Manager
2      2 <NA>  DEF Accountant
3      3 <NA>  GHI         QA
4      4 <NA>  JKL         IT
5      1 <NA>  MNO      Cyber
6      2 <NA>  PQR     Broker
7      3 <NA>  STU        D&T
8      4 <NA>  VWX         IT
> 

CodePudding user response:

Just replace your date format as follows:

df1$date <- as.Date(df1$date, format = "%Y-%m-%d")
df2$date <- as.Date(df2$date, format = "%m/%d/%y")
both <- rbind(df1,df2)
both
  rating       date name      title
1      1 2021-12-19  ABC    Manager
2      2 2021-12-20  DEF Accountant
3      3 2021-12-21  GHI         QA
4      4 2021-12-22  JKL         IT
5      1 2022-12-15  MNO      Cyber
6      2 2022-12-16  PQR     Broker
7      3 2022-12-17  STU        D&T
8      4 2022-12-18  VWX         IT
  •  Tags:  
  • r
  • Related