Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

R: replace NA with fixed date in date column variable (if condition holds)

I would like to replace NA values in a given column (in date format) with a fixed date, if a given condition hold.

In the example below I would like to replace NA values in dt column with "2012-07-01" if condition a==4 holds. I am looking for the simplest way of doing so, either in dplyr or data.table.

> df1 <- data.table(a = c(1, 2, 3, 4),
+                  dt = as.Date(c("2012-06-01", "2012-07-01", NA, NA)))
> df1
   a         dt
1: 1 2012-06-01
2: 2 2012-07-01
3: 3       <NA>
4: 4       <NA>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

With data.table

df1[a == 4 & is.na(dt), dt := as.Date("2012-07-01")]
       a         dt
   <num>     <Date>
1:     1 2012-06-01
2:     2 2012-07-01
3:     3       <NA>
4:     4 2012-07-01

In Base R for completeness:

df1[df1$a == 4 & is.na(df1$dt), "dt"] <- as.Date("2012-07-01")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading