Reputation: 1610
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?
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
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.
Upvotes: 0
Views: 3533
Reputation: 70633
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
Adding data to vectors is through 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"
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
Upvotes: 2
Reputation: 193
Although the solution of @Roman Lustrik works, I think it is simpler:
> 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
Upvotes: 2