Nick Knauer
Nick Knauer

Reputation: 4243

Can't replace NA's with Date

I cannot replace the NA's for some reason even if I use the is.na code. I want to replace the NA with the current date. Any ideas?

Here is what my dataframe looks like:

df 

      Name     Parent        Date
1     A        no parent     OLD
2     B        no parent     NA
3     C        no parent     OLD
4     D        no parent     OLD
5     E        no parent     OLD

When I try this code it doesn't work:

today <- Sys.Date()
df[["Date"]][is.na(df[["Date"]])] <- today

str(df)
'data.frame':   2505 obs. of  3 variables:
 $ Name  : chr  " A" " B"  "C" "D" ...
 $ Parent: chr  "no parent" "no parent" "no parent" "no parent" ...
 $ Date  : chr  "OLD" NA "OLD" "OLD" ...

Upvotes: 1

Views: 3396

Answers (1)

David Arenburg
David Arenburg

Reputation: 92310

A Date in R is just a double with a Date class attribute. Once the attribute stripped off - it just becomes a double. see

attributes(today)
# $class
# [1] "Date"

unclass(today)
# [1] 16897

storage.mode(today) ## data.table::as.IDate uses an integer storage mode
# [1] "double"

And a single column can't hold several classes in R. From [<-.data.frame

When [ is used with a logical matrix, each value is coerced to the type of the column into which it is to be placed.

Investigating the [<-.data.frame documentation I"m not sure how the conversion to a character, happens, probably

as.character(`attributes<-`(today, NULL))
# [1] "16897"

Or

as.character(unclass(today))
# [1] "16897"

While you are looking for

as.character(today)
## [1] "2016-04-06"

So to sum it up, this should do

df[is.na(df$Date), "Date"] <- as.character(today)

Upvotes: 2

Related Questions