我正在尝试从具有2个列的简单数据矩阵计算对数返回。我的以下代码给了我全零,我在这里错过了什么?
dataMatrix<-as.matrix(data[,2:ncol(data)]) #taking data from dataframe
Log_returns<-diff(log(dataMatrix), lag=1)
View(log_returns)
这是数据的前几行
Dates APPL AMZN
1 7-01-2005 4.9464 42.32
2 2005-01-14 5.0143 44.55
3 2005-01-21 5.0350 41.16
4 2005-01-28 5.2843 42.22
5 2005-02-04 5.6314 35.72
6 2005-02-11 5.8007 35.78
7 2005-02-18 6.2007 35.31
8 2005-02-25 6.3564 34.99
9 2005-03-04 6.1157 35.85
10 2005-03-11 5.7529 34.75
答案 0 :(得分:0)
我不确定您要计算的内容。您是要计算每一行APPL
和AMZN
的对数转换后的值之差吗?
Log_returns <- apply(log(data[, 2:ncol(data)]), 1, diff)
# 1 2 3 4 5 6 7 8
#2.146600 2.184318 2.101053 2.078154 1.847353 1.819410 1.739504 1.705600
# 9 10
#1.768484 1.798475
或者保存在新列中
data$Log_return <- apply(log(data[, 2:ncol(data)]), 1, diff)
data
# Dates APPL AMZN Log_return
#1 7-01-2005 4.9464 42.32 2.146600
#2 2005-01-14 5.0143 44.55 2.184318
#3 2005-01-21 5.0350 41.16 2.101053
#4 2005-01-28 5.2843 42.22 2.078154
#5 2005-02-04 5.6314 35.72 1.847353
#6 2005-02-11 5.8007 35.78 1.819410
#7 2005-02-18 6.2007 35.31 1.739504
#8 2005-02-25 6.3564 34.99 1.705600
#9 2005-03-04 6.1157 35.85 1.768484
#10 2005-03-11 5.7529 34.75 1.798475
也许您的意思是计算每个APPL
和AMZN
的连续日期之间对数转换后的值的差异
apply(log(data[, 2:ncol(data)]), 2, diff)
# APPL AMZN
#2 0.013633791 0.051352366
#3 0.004119696 -0.079145243
#4 0.048326634 0.025427131
#5 0.063617919 -0.167183286
#6 0.029620521 0.001678322
#7 0.066683589 -0.013222868
#8 0.024799990 -0.009103904
#9 -0.038602944 0.024281261
#10 -0.061155160 -0.031163995
data <- read.table(text =
" Dates APPL AMZN
1 7-01-2005 4.9464 42.32
2 2005-01-14 5.0143 44.55
3 2005-01-21 5.0350 41.16
4 2005-01-28 5.2843 42.22
5 2005-02-04 5.6314 35.72
6 2005-02-11 5.8007 35.78
7 2005-02-18 6.2007 35.31
8 2005-02-25 6.3564 34.99
9 2005-03-04 6.1157 35.85
10 2005-03-11 5.7529 34.75", header = T)