rdatetimetibble

How to prevent turning a POSIXct variable to number when pulling it out of a tibble and putting it into a list


I'm trying to pull a date from a tibble and place it into a list. (I'm doing this within a function i'm trying to write).

I have tibble, with column (entry_date). It is type double and class POSIXct" "POSIXt".

b <- tibble(visitID = 1:3, 
            entry_date = as.POSIXct(c("2020-04-01 00:00:00 UTC", "2020-04-15 00:00:00 UTC", "2020-05-01 00:00:00 UTC")), 
            propertyID = 1:3, 
            edgeID = 1:3))

I made a list

edge_list <- vector("list", nrow(b)-1)

I'm trying to pull b[[1,2]] and b[[2,2]] out of the tibble and put it in edge_list

edge_list[[1]] = c(visitID = b[[1,1]], 
                   edgeID = b[[1,4]], 
                   start_time= as.POSIXct(as.numeric(b[[1,2]]), origin = "1970-01-01 00:00:00", tzone = "UTC"), 
                   end_time = as.POSIXct(as.numeric(b[[2,2]]), origin = "1970-01-01 00:00:00", tzone = "UTC"))

I've also tried

edge_list[[1]] = c(visitID = b[[1,1]], 
                   edgeID = b[[1,4]], 
                   start_time= b[[1,2]], 
                   end_time = b[[2,2]] )

when I do this - it becomes a number.

> edge_list[[1]]
   visitID     edgeID start_time   end_time 
         1          1 1585717200 1586926800 

> typeof(edge_list[[1]])
[1] "double"
> class(edge_list[[1]])
[1] "numeric"

I've tried converting it back, using similar code from above, but it didn't work. So it's removing the class? and making it numeric? I've found this but it didn't help. How can I prevent this from happening so that I can store the date in the edge_list object. This list will later be appended to a DF, and I need to keep it in the date format throughout the whole process.
Thank you for your help and advice.


Solution

  • The problem is you are combining them using c() which will coerce every element in the same class. See for example,

    c(1, 2, "a")
    #[1] "1" "2" "a"
    
    c(1, Sys.Date(), 2)
    #[1]     1 19879     2
    

    You cannot store elements of different classes in a vector. Try using list/data.frame/tibble.

    edge_list[[1]] = data.frame(visitID = b[[1,1]], 
                       edgeID = b[[1,4]], 
                       start_time= b[[1,2]],
                       end_time = b[[2,2]])
    
    edge_list[[1]]
    #  visitID edgeID start_time   end_time
    #1       1      1 2020-04-01 2020-04-15