R lubridate:如何在数据框中放置一个 lubridate 时间戳?

R lubridate: How to put a lubridate timestamp in a dataframe?

我只是想在数据框中存储 lubridate 时间戳。但是,它们以秒为单位进行转换。

这是一个可重现的例子:

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

所以 tsta 看起来像 "2021-03-16 22:59:59 UTC",但是一旦我把它放在 df 中它看起来像

   timestamp
1 1615935599
2         NA

这样做的正确方法是什么?

matrix 只能存储一个 class 并且 POSIXct 可以转换为其数字存储值。一种选择是

df <- tibble(timestamp = c(tsta, ymd_hms(NA)))

-输出

> df
# A tibble: 2 × 1
  timestamp          
  <dttm>             
1 2021-03-16 22:59:59
2 NA            

或者另一种方式是

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                 

或者使用 OP 的代码,首先转换 NA

df$timestamp <- ymd_hms(df$timestamp)
df[1, 'timestamp'] <- tsta
df
            timestamp
1 2021-03-16 22:59:59
2                <NA>

您可以保存为字符数据,稍后可以转换为 posixct。

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>