3

I have column Aand column B in a dataframe:

A = structure(c(NA, NA, NA, 1559401558, 1559413729, 1559417798), class = c("POSIXct", 
"POSIXt"), tzone = "")

B = structure(c(1559379600, 1559388600, 1559397600, 1559406600, 1559415600, 
1559424600), class = c("POSIXct", "POSIXt"), tzone = "UTC")
> 

As you can see, only column A has missing Dates. I want now, that only the missing Dates in Aare replaced with related values (same indices) in B. I know this should work with indices, but I can't find a solution for this. Thanks for the help!

Mark Szymczyk
  • 17,064
  • 3
  • 51
  • 61

3 Answers3

5

Using Base R:

A[is.na(A)] <- B[is.na(A)]
akash87
  • 3,398
  • 2
  • 11
  • 28
3

We can use coalesce

library(dplyr) 
coalesce(A, B)

As @RuiBarradas mentioned in the comments, we can set the tz to NULL before doing the coalesce

library(lubridate)
coalesce(A, `tz<-`(B, ""))
akrun
  • 674,427
  • 24
  • 381
  • 486
1

With tidyverse:

library(tidyverse)

tibble(A = A, B = B) %>%
 mutate(A = ifelse(is.na(A), B, A))
Ben G
  • 2,903
  • 1
  • 13
  • 33