如何在将POSIXct转换为字符时保留小数位?

5
> t <- Sys.time()
> ct <- as.character(t)
> t - as.POSIXct(ct)
Time difference of 0.4370408 secs

上述示例表明将 POSIXct 转换为字符时会丢失精度。

如何在转换为字符时保留精确值,以便在从字符转换回 POSIXct 时获得原始值?


3
通常最好不要给对象与函数相同的名称;参见 ?t - Jaap
2个回答

4
您可以将选项digits.secs设置为6(其最大值)。
options(digits.secs = 6)

t <- Sys.time()
ct <- as.character(t)
t - as.POSIXct(ct)

Time difference of 0 secs

有没有一种方法可以在不干扰全局选项的情况下完成它? - Bear Bile Farming is Torture

2

您可以使用format%OS6来以数字形式显示秒数,但有时仍会存在差异:

t <- Sys.time()
ct <- format(t, "%Y-%m-%d %H:%M:%OS6")
t - as.POSIXct(ct)
#Time difference of 0 secs

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接