R编程中与datenum相当的函数是什么?

4
我之前有Matlab的经验,但对R很陌生。我遇到的基本问题如下:
我有一组包含10列数据的表格。其中前6列是年、月、日、小时、分钟和秒。
E.g data_example = 
2013 6 15 11 15 0 ...
2013 6 15 11 20 0 ...
2013 6 15 11 25 0 ...

在Matlab中,我用datenum(data_example(:,1:6))轻松地将日期转换成数字进行处理。但在R中,如何获得类似的6列数值表示呢?


你能否发布一份数据样本,并展示一下期望的输出结果是什么? - Roman Luštrik
3个回答

3

以下是一些替代方案。它们都使用了ISOdatetime

1) 假设DF是您的数据框,请尝试像这样使用ISOdatetime

DF$datetime <- ISOdatetime(DF[[1]], DF[[2]], DF[[3]], DF[[4]], DF[[5]], DF[[6]])

2) 或者像这样:

DF$datetime <- do.call(ISOdatetime, setNames(as.list(DF[1:6]), NULL))

3a) 如果这是适合于zoo的时间序列(不同的时间且全部为数字),那么我们可以使用zoo包中的read.zooISOdatetime结合使用,如下所示:

library(zoo)
z <- read.zoo(DF, index = 1:6, FUN = ISOdatetime)

3b) 或使用read.zoo从文件或字符串中读取(后者在此处显示):

# sample input lines
Lines <- "2013 6 15 11 15 0  1
2013 6 15 11 20 0 2
2013 6 15 11 25 0 3
"

library(zoo)
z <- read.zoo(text = Lines, index = 1:6, FUN = ISOdatetime)

这给出了这个动物园系列:
> z
2013-06-15 11:15:00 2013-06-15 11:20:00 2013-06-15 11:25:00 
                  1                   2                   3 

0
使用Lubridate包中的parse_date_time函数。
x <- paste0(data_example[,1:6])
x <- parse_date_time(x,"%y%m%d %H%M")

文档中获取更多信息。

编辑 @joran告诉我要测试一下,但它没有起作用,所以我做了一些修改:

data_example = data.frame(t(c(13,2,9,14,30)))
x <- paste0(data_example[,1:3],collapse="-")
y <- paste0(data_example[,4:5],collapse=":")
xy<- paste(x,y)
xy <- parse_date_time(xy,"%y%m%d %H%M")
xy
# "2013-02-09 14:30:00 UTC"

我不知道是否有更简洁的方法来做这件事


我觉得在 data_example(:,1:6) 中混杂了一些 MATLAB 语法。 - joran
这至少是R代码,但我不认为它会做你想要的事情。在一个小的数据框上试一下吧。 - joran

0

在R中,返回值的单位与Matlab略有不同(请参见代码中的注释)。此外,由于您的数据框中还有其他列,因此您需要首先将数据框子集化以仅包含相关的(6个)日期列,然后将它们作为新列添加到数据框的末尾。

test <- data.frame("year"=c(2013, 2013, 2013, 2001, 1970)
                   , "month"=c(6,6, 6, 4, 1)
                   , "day"=c(15,15, 15, 19, 1)
                   , "hour"=c(11,11, 11, 11, 0)
                   , "min"=c(15,20, 25, 30, 0)
                   , "second"=c(0,0, 0 ,0, 0))
# pad to the right # of digits
dates00 <- apply(test, c(1,2), sprintf, fmt="%02s") 
# combine the date components in each row into a single string
dates0 <- apply(dates00, 1, paste, collapse=" ") 
#format to a date object
dates <- as.POSIXct(dates0, format="%Y %m %d %H %M %S") 
# numbers are seconds since "1970-01-01 00:00:00 UTC"; according 
# to the help file for daynum, Matlab returns the number (from 
# daynum) as fractional days since "January 0, 0000"
as.numeric(dates)

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