将日期添加到数据向量

时间:2013-06-27 07:24:25

标签: r datetime

我在使用R时遇到一点麻烦,并在数据向量中添加日期。我想我用错误的方式弄乱了对象?

数据:y(即数字[9])

y <-data.frame
y
temp     cons     wind      ror      solar   nuclear   chp       net    thermal  
0.5612   0.5065   0.1609   0.2989   0.7452   0.9621   0.2810   0.6998   0.4519 

我想在包含今天日期的开头添加一个列,所以它看起来像:

date           temp     cons     wind      ror      solar   nuclear   chp       net    thermal  
28-06-2013    0.5612   0.5065   0.1609   0.2989   0.7452   0.9621   0.2810   0.6998   0.4519 

我使用Sys.Date()+ 1来获取明天的日期,但是当我用我的数据进行cbind时,我会收到一些不需要的结果,例如:

tomorrow<-Sys.Date()+1
cbind(tomorrow, y)
vector      y
temp      15884 0.5612
cons      15884 0.5065
wind      15884 0.1609
ror       15884 0.2989
solar     15884 0.7452
nuclear   15884 0.9621
chp       15884 0.2810 
net       15884 0.6998
thermal   15884 0.4519

我不希望以这种数字格式显示日期,我不太清楚数据突然变成矩阵变量的原因。

2 个答案:

答案 0 :(得分:2)

你没有data.frame,你有一个向量。您可以将数据附加到矢量,如下所示:

y <- rnorm(10)
names(y) <- letters[1:10]
cbind(Sys.Date(), y) # vector, see?

                  y
a 15883 -1.21566678
b 15883  0.98836517
c 15883 -1.01564976
d 15883 -0.59483533
e 15883 -0.40890915
f 15883  1.69711341
g 15883  0.05012548
h 15883  0.42253546
i 15883  1.05420278
j 15883  0.15760482

向向量添加数据是通过c

c(Sys.Date(), y)

                        a            b            c            d            e            f            g            h            i 
"2013-06-27" "1969-12-30" "1970-01-01" "1969-12-30" "1969-12-31" "1969-12-31" "1970-01-02" "1970-01-01" "1970-01-01" "1970-01-02" 
           j 
"1970-01-01" 

要强制使用data.frame并cbind数据,请执行此操作。

y <- data.frame(matrix(y, nrow = 1, dimnames = list(1, names(y))))
cbind(Sys.Date(), y)

  Sys.Date()         a          b         c        d         e         f        g        h         i         j
1 2013-06-27 0.3946908 0.09510043 0.9753345 -1.05999 -1.041331 0.5796274 0.125427 1.319828 -1.844391 0.3365856

答案 1 :(得分:2)

虽然@Roman Lustrik的解决方案有效,但我认为它更简单:

> y$date <- Sys.Date()
> y
          a        b         c        d          e          f          g          h          i        j
1 -1.104803 1.184856 0.9791311 1.866442 -0.3385167 0.04975147 -0.1821668 -0.7745292 -0.9261035 1.021533
        date
1 2013-06-27