Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overwriting only NAs in column A with values from column B [duplicate]

Tags:

r

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!

like image 585
Björn Butter Avatar asked Jan 17 '26 08:01

Björn Butter


2 Answers

Using Base R:

A[is.na(A)] <- B[is.na(A)]
like image 148
akash87 Avatar answered Jan 19 '26 22:01

akash87


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, ""))
like image 40
akrun Avatar answered Jan 19 '26 21:01

akrun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!