user3385769
user3385769

Reputation: 161

binding dates in data frame

I am trying to understand, why what I am doing is not working, and why I am receiving the results that I am. Both the reason why when I have a single column of data frame and try to add a row, I am expanding it somehow, and also why are the formats of the dates changing? If anybody could please help out, in addition to knowing the proper way, I am really interested in knowing the reason why it doesn't work.

thanks

class(wklyAvg.hedge.cost$Date[[NROW(wklyAvg.hedge.cost)]]+7)
[1] "Date"

class(wklyAvg.hedge.cost$Date[2:NROW(wklyAvg.hedge.cost$Date)])
[1] "Date"

head(wklyAvg.hedge.cost$Date[2:NROW(wklyAvg.hedge.cost$Date)])
[1] "1997-01-10" "1997-01-17" "1997-01-24" "1997-01-31" "1997-02-07" "1997-02-14"

wklyAvg.hedge.cost$Date[[NROW(wklyAvg.hedge.cost)]]+7
[1] "2014-01-10"

hedge.apply.dates <- rbind(wklyAvg.hedge.cost$Date[2:NROW(wklyAvg.hedge.cost$Date)],wklyAvg.hedge.cost$Date[[NROW(wklyAvg.hedge.cost)]]+7)

head(hedge.apply.dates)
      [,1]  [,2]  [,3]  [,4]  [,5]  [,6]  [,7]  [,8]  [,9] [,10] [,11] [,12] [,13] [,14] [,15] [,16] [,17] [,18] [,19] [,20] [,21] [,22] [,23] [,24] [,25] [,26] [,27] [,28] [,29] [,30] [,31] [,32] [,33] [,34] [,35] [,36] [,37]
[1,]  9871  9878  9885  9892  9899  9906  9913  9920  9927  9934  9941  9948  9955  9962  9969  9976  9983  9990  9997 10004 10011 10018 10025 10032 10039 10046 10053 10060 10067 10074 10081 10088 10095 10102 10109 10116 10123
[2,] 16080 16080 16080 16080 1608

Upvotes: 1

Views: 2133

Answers (2)

Roland
Roland

Reputation: 132706

rbind binds rows. Since your two vectors are not of the same length, the shorter is recycled. Also, as help("rbind") points out, "any classes the inputs might have are discarded". Thus you end up with the internal integer representation of the Dates in a two-row matrix.

a <- as.Date(c("1997-01-10", "1997-01-17", "1997-01-24", "1997-01-31", "1997-02-07", "1997-02-14"))
b <- as.Date("2014-01-10")
rbind(a, b)
#   [,1]  [,2]  [,3]  [,4]  [,5]  [,6]
#a  9871  9878  9885  9892  9899  9906
#b 16080 16080 16080 16080 16080 16080

Possibly you'd like to use c (which creates a vector) instead?

c(a, b)
#[1] "1997-01-10" "1997-01-17" "1997-01-24" "1997-01-31" "1997-02-07" "1997-02-14" "2014-01-10"

Upvotes: 1

jtanman
jtanman

Reputation: 684

Just do this instead

hedge.apply.dates <- c(wklyAvg.hedge.cost$Date[2:NROW(wklyAvg.hedge.cost$Date)],wklyAvg.hedge.cost$Date[[NROW(wklyAvg.hedge.cost)]]+7)

Upvotes: 1

Related Questions