Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does unlist() kill dates in R?

Tags:

r

When I unlist a list of dates it turns them back into numerics. Is that normal? Any workaround other than re-applying as.Date?

> dd <- as.Date(c("2013-01-01", "2013-02-01", "2013-03-01")) > class(dd) [1] "Date" > unlist(dd) [1] "2013-01-01" "2013-02-01" "2013-03-01" > list(dd) [[1]] [1] "2013-01-01" "2013-02-01" "2013-03-01"  > unlist(list(dd)) [1] 15706 15737 15765 

Is this a bug?

like image 789
Thomas Browne Avatar asked Mar 27 '13 13:03

Thomas Browne


People also ask

What does the function unlist () do R?

unlist() function in R Language is used to convert a list to vector. It simplifies to produce a vector by preserving all components.

How do I unlist a matrix in R?

To convert R List to Matrix, use the matrix() function and pass the unlist(list) as an argument. The unlist() method in R simplifies it to produce a vector that contains all the atomic components which occur in list data.


1 Answers

do.call is a handy function to "do something" with a list. In our case, concatenate it using c. It's not uncommon to cbind or rbind data.frames from a list into a single big data.frame.

What we're doing here is actually concatenating elements of the dd list. This would be analogous to c(dd[[1]], dd[[2]]). Note that c can be supplied as a function or as a character.

> dd <- list(dd, dd) > (d <- do.call("c", dd)) [1] "2013-01-01" "2013-02-01" "2013-03-01" "2013-01-01" "2013-02-01" "2013-03-01" > class(d) # proof that class is still Date [1] "Date" 
like image 152
Roman Luštrik Avatar answered Sep 20 '22 22:09

Roman Luštrik