数据框中的绑定日期

时间:2014-10-30 15:30:38

标签: r date dataframe rbind

我想了解,为什么我在做什么不起作用,为什么我收到的结果是我。这两个原因当我有一列数据框并尝试添加一行时,我正在以某种方式扩展它,以及为什么日期的格式会发生变化?如果有人可以请求帮助,除了知道正确的方法之外,我真的很想知道它不起作用的原因。

感谢

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

2 个答案:

答案 0 :(得分:1)

rbind绑定行。由于您的两个向量长度不同,因此较短的回收率。此外,正如help("rbind")指出的那样,“输入可能具有的任何类都被丢弃”。因此,您最终会在两行矩阵中得到Date s的内部整数表示。

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

您可能想要使用c(创建向量)吗?

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"

答案 1 :(得分:1)

改为执行此操作

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