Adding date to a vector of data

前端 未结 2 328
有刺的猬
有刺的猬 2020-12-22 08:28

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])

<
相关标签:
2条回答
  • 2020-12-22 08:47

    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
    
    0 讨论(0)
  • 2020-12-22 08:49

    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
    
    0 讨论(0)
提交回复
热议问题