2014-06-06 237 views
1

我有一个XTS数据集,其中包含许多股票收盘价,名为:dataset。然后我想通过cor()找到他们的退货是否有任何关联,但是我收到一条错误消息:Error in cor(RETS) : 'x' must be numeric相关性错误:'x'必须为数字

这里是我做了什么:

RETS <- CalculateReturns(dataset, method= c("log")) # Calculate returns Via PerformanceAnalytics 
RETS<- na.locf(RETS) #Solves missing NAs by carrying forward last observation 
RETS[is.na(RETS)] <- "0" #I then fill the rest of the NAs by adding "0" 

这里是RETS

row.names A.Close AA.Close AADR.Close AAIT.Close AAL.Close 
1 2013-01-01 0   0   0   0   0 
2 2013-01-02 0.0035  0.0088  0.0044  -0.00842 0 
3 2013-01-03 0.0195  0.0207  -0.002848 -0.00494 0 
4 2013-01-06 -0.0072  -0.0174  0.0078  -0.00070 0 
5 2013-01-07 -0.0080  0   -0.01106  -0.03353 0 
6 2013-01-08 0.0266  -0.002200 0.006655  0.0160  0 
7 2013-01-09 0.0073  -0.01218  0.007551  0.013620 0 

的样本。然后我执行的相关性:

#Perform Correlation 
cor(RETS) -> correl 
Error in cor(RETS1) : 'x' must be numeric 

#Tried using as.numeric 
cor(as.numeric(RETS), as.numeric(RETS) -> correl 

然而,答案是“1 ”。我也尝试使用psych中的相关函数,但得到相同的错误消息。

+0

你能告诉我们'typeof(RETS)'的结果吗? – Pop

+0

@Pop是的,'typeof(RETS)=“字符”' – Jason

+2

你的问题是什么?通过使用'RETS [is.na(RETS)] < - “0”',您可以将所有数据转换为字符,并且无法计算字符的相关性。 – Roland

回答

3

我在@ Roland的答案中添加了关闭问题的地方。

的问题是,使用

RETS[is.na(RETS)] <- "0" 

是因为添加任何字符值到一个数字值自动改变data.types到字符转动所有的数据转换成字符。因此,当你去进行关联时,没有办法为角色值做到这一点。所以,如果你只是做

RETS[is.na(RETS)] <- 0 

相反,你应该避免转换问题。

而不是你的遗漏值设置为NA,您也可以考虑明确地告诉cor如何处理缺失值例如

cor(RETS, use="pairwise.complete.obs") 

将只计算两个变量对那些对其中两个是不-NA之间的相关性。有关所有选项,请参阅?cor帮助页面。

相关问题