创建循环以在 R 中索引值
Creating Loop to indexing values in R
我通过雅虎财经、路透社和其他来源下载了几个时间序列。
它们都列为单独的 "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)
}
}
不幸的是,它 returns 除了最后一个之外只有 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
你能帮帮我吗?
非常感谢。
这里有一个适用于 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"-对象,其中包含各自的收盘价。这些向量可用于每日和每月间隔。
我想创建一个图表来显示我的股票的价格走势。 这张图表应该是第一天的相对价格走势:
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)
}
}
不幸的是,它 returns 除了最后一个之外只有 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
你能帮帮我吗?
非常感谢。
这里有一个适用于 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)