将日期添加到数据向量 [英] Adding date to a vector of data

查看:107
本文介绍了将日期添加到数据向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用R时遇到了一些麻烦,并将日期添加到了数据向量中。我猜我在用错误的方式摆弄物体?

Im having a little trouble with R and adding a date to a vector of data. I guess i'm messing around with objects the wrong way?

数据:y(数字[9])

Data: y (that is numeric[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 

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

I want to add a column in at the start that contains todays date, so it will look like:

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获取明天的日期,但是当我将其与数据绑定时,会得到一些不需要的结果,例如:

Im using Sys.Date()+1 to get the date of tomorrow, but when I cbind it with my data, I get some unwanted results, like:

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

我不希望日期以这种数字格式显示,而且我不太确定为什么数据突然变成矩阵变量。

I don't want the date displayed in this numeric format, and im not quite sure why the data suddenly becomes a matrix variable.

推荐答案

您没有data.frame,而是矢量。您可以像这样将数据附加到向量上:

You don't have a data.frame, you have a vector. You can append data to a vector like so:

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并绑定数据,请执行此操作。

To coerce to a data.frame and cbind the data, do this.

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

这篇关于将日期添加到数据向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆