I am simply trying to store lubridate
timestamps in a dataframe. However, they get converted in number of seconds.
Here's a reproducible example:
library(lubridate)
tsta <- ymd_hms('2021-03-16 22:59:59') # tsta for timestamp
df <- as.data.frame(matrix(ncol=1, nrow=2)) # preallocate a small dataframe
colnames(df) <- 'timestamp'
# trying to add lubridate object in it
df[1, 'timestamp'] <- tsta
So tsta
looks like "2021-03-16 22:59:59 UTC"
, but once I put it in df
it looks like
timestamp
1 1615935599
2 NA
What's the proper way of doing this?
CodePudding user response:
matrix
can store only a single class and POSIXct
can get converted to its numeric storage values. One option is
df <- tibble(timestamp = c(tsta, ymd_hms(NA)))
-output
> df
# A tibble: 2 × 1
timestamp
<dttm>
1 2021-03-16 22:59:59
2 NA
Or another way is
df <- tibble(timestamp = ymd_hms(rep(NA, 2)))
df$timestamp[1] <- tsta
df
# A tibble: 2 × 1
timestamp
<dttm>
1 2021-03-16 22:59:59
2 NA
Or using the OP's code, the NA
values are converted first
df$timestamp <- ymd_hms(df$timestamp)
df[1, 'timestamp'] <- tsta
df
timestamp
1 2021-03-16 22:59:59
2 <NA>
CodePudding user response:
You might save as character data that could be converted to posixct later.
tsta <- format(ymd_hms('2021-03-16 22:59:59'), "%Y-%m-%d %H:%M:%S")
df[1, 'timestamp'] <- tsta
df
timestamp
1 2021-03-16 22:59:59
2 <NA>