rubengura
rubengura

Reputation: 469

Convert multiple character vectors to date with apply returns a number in R

I have a df with 4 date columns as character vectors:

print(df)
       Date1      Date2      Date3      Date4
1 2016-12-05       <NA> 2016-11-24 2017-12-05
2 2007-10-15 2009-09-18 2007-10-15 2017-10-15
3 2005-07-22 2009-06-20 2005-07-22 2017-07-22
4 2008-01-03 2017-07-25 2008-01-03 2018-01-03

If I apply:

df <- apply(df, 2, function(x) as.Date(x, origin = "1970-01-01")) 

I get as a result:

print(df)
     Date1 Date2 Date3 Date4
[1,] 17140    NA 17129 17505
[2,] 13801 14505 13801 17454
[3,] 12986 14415 12986 17369
[4,] 13881 17372 13881 17534

I've solved the problem using lapply instead of apply but I would like to know what is happening inside apply for returning dates as a number.

Upvotes: 0

Views: 47

Answers (1)

Uwe
Uwe

Reputation: 42564

The OP would like to know what is happening inside apply for returning dates as a number.

The help page ?apply says

In all cases the result is coerced by as.vector to one of the basic vector types before the dimensions are set

The help page ?as.vector says

All attributes are removed from the result if it is of an atomic mode, but not in general for a list result.

As already mentioned by Akarsh Jain, Date objects have a class attribute. Removing the class attribute will leave just the plain number of days since 1970-01-01.

Here is a code snippet for demonstration:

x <- as.Date("2016-12-05")
x
#> [1] "2016-12-05"
attributes(x)
#> $class
#> [1] "Date"
y <- as.vector(x)
y
#> [1] 17140
attributes(y)
#> NULL

Upvotes: 1

Related Questions