R 在列表中向日期项追加字符串时,如何保持POSIXct格式?

R 在列表中向日期项追加字符串时,如何保持POSIXct格式?,r,R,此处时间添加到列表中,列表转换为字符串: str(list(Sys.time())) 输出为: POSIXct[1:1], format: "2017-11-10 21:22:56" 如何将字符串粘贴到列表项并保持格式? 应将其输出: List of 1 $ : Time : POSIXct[1:1], format: "2017-11-10 21:22:56" 我试过: str(list(paste("time" , Sys.time()))) str(list(c("tim

此处时间添加到列表中,列表转换为字符串:

str(list(Sys.time()))
输出为:

  POSIXct[1:1], format: "2017-11-10 21:22:56"
如何将字符串粘贴到列表项并保持格式? 应将其输出:

  List of 1
  $ : Time : POSIXct[1:1], format: "2017-11-10 21:22:56"
我试过:

str(list(paste("time" , Sys.time())))
str(list(c("time" , Sys.time())))
但结果是:

> str(list(paste("time" , Sys.time())))
List of 1
$ : chr "time 2017-11-10 21:23:23"
> str(list(c("time" , Sys.time())))
List of 1
$ : chr [1:2] "time" "1510349011.98052"

您必须对捕获的输出执行字符串操作:

writeLines(sub('$ : ', '$: time :', capture.output(str(list(Sys.time()))), fixed=T))
## List of 1
## $: time :POSIXct[1:1], format: "2017-11-10 16:34:47"
虽然我不得不说,我不完全确定你这么做是为了什么

str(list(paste("time" , Sys.time())))
这是长度为1的列表,1元素来自
paste
,它将返回一个字符串,因为这就是
paste
的作业。因此
str
报告了chr类型的长度1的列表

str(list(c("time" , Sys.time())))
这也是长度1的列表,1元素是字符串“time”的向量(由
c
创建)和
Sys.time()
中的
POSIXct
对象。向量只能存储一种东西,因此R必须将所有东西都转换为字符

有趣的是,向量中POSIXct元素转换为chr的方式取决于向量中的第一个元素是什么:

> str(c("this",Sys.time()))
 chr [1:2] "this" "1510353128.84358"

> str(c(Sys.time(),"this"))
 POSIXct[1:2], format: "2017-11-10 22:33:13" NA
 Warning message:
 In as.POSIXlt.POSIXct(x, tz) : NAs introduced by coercion
因为R使用第一个元素来确定要使用哪种转换方法。如果第一个元素是字符,它使用
as.character.default
将POSIXt对象转换为数字,因为它们实际上只是数字,而
as.character.default
不理解POSIXt时间戳:

> as.character.default(Sys.time())
[1] "1510353378.21108"
如果第一个元素或所有元素都是POSIX对象,那么您会得到一个格式化的时间戳:

> as.character.POSIXct(Sys.time())
Error in as.character.POSIXct(Sys.time()) : 
  could not find function "as.character.POSIXct"
> as.character.POSIXt(Sys.time())
[1] "2017-11-10 22:36:30"
这失败了:

> str(c(Sys.time(),"this"))
 POSIXct[1:2], format: "2017-11-10 22:33:13" NA
 Warning message:
 In as.POSIXlt.POSIXct(x, tz) : NAs introduced by coercion
因为它试图对字符串“this”调用
as.POSIXlt.POSIXct


明白了吗?可能不会。基本上,在开始将字符串粘贴在一起之前,您应该弄清楚您想要什么,并将数据元素格式化为字符。

您想要的输出可能无法用
str
完成。你为什么想要精确的输出?你知道在R中字符和数字是如何粘贴在一起的吗?或者
c()
list()
之间的区别?@Spacedman我想要这个输出,因为我不知道为什么在使用“c”或“粘贴”时输出会改变。没有什么特别的原因,除了结果不是我所期望的。
> as.POSIXlt.POSIXct("this")
[1] NA
Warning message:
In as.POSIXlt.POSIXct("this") : NAs introduced by coercion
>