【问题标题】:Creating Loop to indexing values in R在R中创建循环以索引值
【发布时间】:2019-05-04 21:43:16
【问题描述】:

我通过 Yahoo-Finance、路透社和其他来源下载了多个时间序列。

它们都被列为单独的“xts”对象,其中包含各自的收盘价。这些向量可用于每日和每月间隔。

我想创建一张图表来显示我的股票价格走势。 这张图表应该是相对于第一天的价格走势:

price of 2005-01-04/price of 2005-01-03 
price of 2005-01-05/price of 2005-01-03

等等。

为此,我尝试创建一个 for 循环:

indexfun <- function(x)
  {
  y <- as.matrix(x)
  z <- rep(NULL, nrow(x))
  for(i in nrow(y)){
  z[i] <- y[i,1]/y[1,1]
    print(z)
  }
}

不幸的是,它返回唯一的 NA 值,除了最后一个。 我尝试将向量保存为矩阵,以确保我可以访问包含收盘价的列并且保持日期不变。

我的 xts-vector 看起来像

           BA.close
2005-01-03    50.97
2005-01-04    49.98
2005-01-05    50.81
2005-01-06    50.48
2005-01-07    50.31
2005-01-10    50.98

你能帮帮我吗?

非常感谢。

【问题讨论】:

标签: r loops for-loop indexing na


【解决方案1】:

这里有一个适用于xts 的解决方案:

library(xts)

x <- xts(c(50.97, 49.98, 50.81, 50.48, 50.31, 50.98),as.Date("2005-01-03")+0:5)

x / drop(coredata(x['2005-01-03']))


                [,1]
2005-01-03 1.0000000
2005-01-04 0.9805768
2005-01-05 0.9968609
2005-01-06 0.9903865
2005-01-07 0.9870512
2005-01-08 1.0001962

如果您有更多列,每列都是不同的股票,并且您想除以相同的日期:

首先将您的数据转换为matrix 并删除日期列(稍后将其放回原处),请记住我们使用第一行进行划分。

mat <- as.matrix(d[,-1]) # remove the dates

sweep(mat,2,mat[1, ],`/`) # divide by mat[1, ]. i.e. first row
#            aaa      bbb
# [1,] 1.0000000 1.000000
# [2,] 0.9805768 2.090909
# [3,] 0.9968609 4.090909
# [4,] 0.9903865 5.090909
# [5,] 0.9870512 7.818182
# [6,] 1.0001962 3.090909
# now we can trasform back to data.frame and cbind() with the dates.

使用的数据:

tt <- "date     aaa     bbb
2005-01-03    50.97     11
2005-01-04    49.98     23
2005-01-05    50.81     45
2005-01-06    50.48     56
2005-01-07    50.31     86
2005-01-10    50.98     34"

d <- read.table(text=tt, header=T)

【讨论】:

  • 每只股票都有其单一的收盘价向量,格式为 xts。
  • 您的第一种方法提供:> index_boeing_daily ts_boeing_daily %>% + mutate(new = BA. close/ts_boeing_daily$BA.close[date=="2005-01-03"]) UseMethod("mutate_") 中的错误:没有适用于 'mutate_' 的方法应用于类“c('xts', '动物园')"
  • 抱歉,现在我已经更新了xts 对象的解决方案。
  • 非常感谢!!你让我今天一整天都感觉很好 :)。谢谢。
猜你喜欢
  • 2019-08-26
  • 2017-12-29
  • 1970-01-01
  • 1970-01-01
  • 2017-01-17
  • 1970-01-01
  • 2020-08-19
  • 2021-12-08
  • 2015-05-28
相关资源
最近更新 更多