r - R lubridate: How to put a lubridate timestamp in a dataframe?
问题描述
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?
解决方案
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>
推荐阅读
- java - AnyLogic,具有特定代理条件的资源选择
- security - 如何在 OWASP 测试中为 POST、PUT、PATCH 方法生成数据?
- javascript - 添加在使用 javascript 加载网站时不需要可见的大部分 HTML 是否是一种不好的做法?
- pdf - Puppeteer PDF,页脚和内容在同一行?
- php - PHP中的数组比较和重新排序
- azure-ad-b2c - Azure Active Directory B2C - IE 问题
- r - caret::train 包中 type = 'prob' 参数的问题
- loops - ASP.Net Core MVC 更新模型
- typescript - 如何在单击按钮时在 nginx 中的多个页面中重定向
- react-native - React Native Production App 在异常时显示空白屏幕