【问题标题】:correlation error: 'x' must be numeric相关错误:“x”必须是数字
【发布时间】:2014-07-27 09:51:36
【问题描述】:

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

这是我所做的:

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 中使用相关函数,但得到相同的错误消息。

【问题讨论】:

  • 你能告诉我们typeof(RETS)的结果吗?
  • @Pop 是的,typeof(RETS) = "character"
  • 您的问题是什么?通过使用RETS[is.na(RETS)] &lt;- "0",您可以将所有数据转换为字符,并且无法计算字符的相关性。
  • +1 @Roland 评论。你应该做RETS[is.na(RETS)] &lt;- 0。此外,correl 应该是矩阵,因为您的 data.frame RETS 有几列
  • @Roland 哦,现在我明白了。这使它现在可以工作了,谢谢大家!

标签: r numeric xts correlation stocks


【解决方案1】:

我正在添加@Roland 的答案以结束问题。

问题在于使用

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

将所有数据转换为字符,因为将任何字符值添加到数值会自动将 data.types 更改为字符。因此,当您进行相关时,无法对字符值执行此操作。所以如果你只是这样做

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

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

除了将您的缺失值设置为NA,您还可以考虑明确告诉cor 如何处理缺失值例如

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-04
    • 2021-12-29
    • 2023-04-07
    • 1970-01-01
    • 2020-12-19
    • 2019-01-08
    • 2022-01-05
    相关资源
    最近更新 更多