as.Date returning number when overriding old date

Viewed 61

I got this piece of code:

tel = data.frame(s = c(1,2,3))
tel <- tel %>% mutate(datum = as.Date("19001212", "%Y%m%d"))
tel <- tel %>% mutate(datum = ifelse(s == 1, as.Date("20191211", "%Y%m%d"), datum))

When this code runs it adds a column datum containing the date to a data frame on line 2. Then on line 3 it tries to change this date for rows in which s has the value 1. However for some reason it does not insert the new date in the but the number 18241 and changes all other datum fields (for the other rows into -25222.

What causes this and how do I fix it so it overrides the data set correctly?

3 Answers

dplyr package has if_else, which seems to work

tel %>% mutate(datum = if_else(s == 1, as.Date("20191211", "%Y%m%d"), datum))

It's the ifelse that internally coerces dates into numerics. I suggest to simply subset your data to replace the values. I show a replacement of your line 3 here:

tel[tel$s == 1, "datum"] <- as.Date("20191211", "%Y%m%d")
tel
#   s      datum
# 1 1 2019-12-11
# 2 2 1900-12-12
# 3 3 1900-12-12

Will trying like this work?

> tel %>% mutate(datum = as.Date(ifelse(s == 1, "20191211", "19001212"), "%Y%m%d"))
  s      datum
1 1 2019-12-11
2 2 1900-12-12
3 3 1900-12-12
> 
Related