在下面的代码中,最后一个和倒数第二个 R 代码产生的结果有点不同,为什么?运行最后一行后,为什么我没有得到输出“时间差是 5 分钟的时间差”? 我怎样才能得到这样的输出?
filenames <- c("CH7Data_20130401T130110.csv", "CH7Data_20130401T130610.csv")
timestamps <- gsub(".*_([^.]+).*", "\\1", filenames)
## [1] "20130401T130110" "20130401T130610"
timestamps <- as.POSIXlt(timestamps, format = "%Y%m%dT%H%M%S")
## [1] "2013-04-01 13:01:10 PDT" "2013-04-01 13:06:10 PDT"
timestamps[2]-timestamps[1]
##Time difference of 5 mins
cat("time difference is",timestamps[2]-timestamps[1])
##time difference is 5
最佳答案
'difftime'-对象是具有特殊类的原子对象,因此它们有一个打印方法,可以更改在控制台上看到的输出。如果您希望如评论中所述打印一条冗余消息,其中包括控制台的内容和某种序言,那么这将起作用:
> cat("time difference is",capture.output(timestamps[2]-timestamps[1]) )
time difference is Time difference of 5 mins
您可以在序言文本末尾插入换行符:
> cat("time difference is\n",capture.output(timestamps[2]-timestamps[1]) )
time difference is
Time difference of 5 mins
关于R时间戳差异打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25494999/