简体   繁体   English

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

[英]R lubridate: How to put a lubridate timestamp in a dataframe?

I am simply trying to store lubridate timestamps in a dataframe.我只是想在数据帧中存储lubridate时间戳。 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所以tsta看起来像"2021-03-16 22:59:59 UTC" ,但是一旦我把它放在df它看起来像

   timestamp
1 1615935599
2         NA

What's the proper way of doing this?这样做的正确方法是什么?

matrix can store only a single class and POSIXct can get converted to its numeric storage values. matrix只能存储一个类,而POSIXct可以转换为其数字存储值。 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或者使用 OP 的代码,首先转换NA

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

You might save as character data that could be converted to posixct later.您可以保存为字符数据,稍后可以将其转换为 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM