J.W*_*W.D 2 r matrix correlation dataframe
我在尝试从相关矩阵中提取数据时遇到了一些困难,我希望提取高于 0.8 且低于 0.99 的值,因为我想排除恰好为 1 的两只股票的相关性。
这是我的代码:
#Test
#load the packages
library(corrr)
library(ggplot2)
library(ggcorrplot)
library(dplyr)
library(quantmod)
#get the data needed
startdate <- "2001-01-03"
tickers <- c("MMM", "AA", "AXP", "T", "BAC")
portfolioprices <- NULL
for(ticker in tickers)
portfolioprices <- cbind(portfolioprices, getSymbols(ticker, from=startdate, auto.assign=F)[,4])
colnames(portfolioprices) <- tickers
#check if there is nothing wrong with the data
print(portfolioprices)
#create a correlation matrix and plot it
correlations <- cor(as.matrix(portfolioprices))
correlations <- as.data.frame(correlations)
correlations
ggcorrplot(correlations, hc.order = TRUE, type = "lower",
lab = TRUE)
Run Code Online (Sandbox Code Playgroud)
作为输出我得到:
MMM AA AXP T BAC
MMM 1.0000000 -0.40325223 0.8772498 0.39019025 -0.2406640
AA -0.4032522 1.00000000 -0.3029517 0.06347736 0.8383226
AXP 0.8772498 -0.30295171 1.0000000 0.41189453 -0.1304659
T 0.3901902 0.06347736 0.4118945 1.00000000 -0.1297723
BAC -0.2406640 0.83832262 -0.1304659 -0.12977234 1.0000000
Run Code Online (Sandbox Code Playgroud)
这是我理想情况下提取与最小值 0.8 正相关的数据的数据框。
我不知道我的做法是否完全错误,欢迎任何反馈!
编辑:
理想情况下,我希望数据如下所示:
MMM AA AXP T BAC
MMM 0.8772498
AA 0.8383226
AXP 0.8772498
T
BAC 0.83832262
Run Code Online (Sandbox Code Playgroud)
只有相关的正值才会被过滤。删除不相同的值。
MMM:AXP = 0.8772498 BAC:AA = 0.8382262
如果这可能的话。
预先非常感谢您!
只需在代码末尾添加这一行
correlations[correlations < 0.8 | correlations ==1] <- ""
Run Code Online (Sandbox Code Playgroud)
希望能帮助到你!
| 归档时间: |
|
| 查看次数: |
11183 次 |
| 最近记录: |