【问题标题】:Incorrect output of findCorrelation (caret package)findCorrelation 的错误输出(插入符号包)
【发布时间】:2016-03-14 10:23:20
【问题描述】:

我使用 caret 包的“findCorrelation”函数来定义相关性等于或低于截止(阈值)集的因子。我的脚本如下:

library (caret)
set.seed(123)
#make a matrix to calculate correlation
data<-as.matrix(data.frame(x=rnorm(1:1000),y=rnorm(1:1000),z=rnorm(1:1000),w=rnorm(1:1000)))
#calculate correlation
df2 <- cor(data)
hc <- findCorrelation(as.matrix(df2), cutoff=0.05) # putt any value as a "cutoff"
hc <- sort(hc)
print(df2)
print(df2[-hc,-hc])

df2 输出(所有因素): 打印(df2)

      x            y           z            w  

x 1.00000000 0.086479441 -0.01932954 -0.002994710
y 0.08647944 1.000000000 0.02650333 -0.007029076
z -0.01932954 0.026503334 1.00000000 0.050560850
w -0.00299471 -0.007029076 0.05056085 1.000000000

df2 应用截止值为 0.05:

print(df2[-hc,-hc])
      x           w  

x 1.00000000 -0.00299471
w -0.00299471 1.00000000

但是,如果我应用 cutoff=0.1,例如,我将有一个零矩阵,而不是低于 cutoff 的所有因素的列表:

hc <- findCorrelation(as.matrix(df2), cutoff=0.1) 
hc <- sort(hc)
print(df2[-hc,-hc])  

cutoff=0.1 的 df2 输出:

我已经从我的业务案例中运行了其他示例,并且似乎至少有一个因子高于临界值以生成低于临界值的因子矩阵。
否则,生成零矩阵。

我已经深入研究了“findCorrelation”的脚本,但它运行良好。也许脚本不被认为可以处理这种情况。

因此,我将不胜感激您提供如何解决该问题的提示。

2016 年 7 月 3 日更新:
由于@topepo 的有用回答,我修改了脚本:

要更换的部分:

print(df2[-hc,-hc])  

与:

if(length(hc)==0){
  print(df2)
}else{
  print(df2[-hc,-hc])
}

【问题讨论】:

    标签: r matrix r-caret


    【解决方案1】:

    这不是错误。

    ?findCorrelation中,将返回值描述为

    表示要删除的列的索引向量(当names = TRUE 时)否则为列名向量。如果没有符合条件的关联,则返回integer(0)

    您看到结果的问题是因为您需要确保子集向量通过类似的方式包含元素

    if(length(hc) > 0) df2 <- df2[-hc, -hc]

    任何零长度整数都会产生这个问题。

    【讨论】:

    • 感谢您的回答。我已经查看了我的可重现脚本并进行了正确的修改
    猜你喜欢
    • 2016-05-07
    • 2017-05-19
    • 2016-03-24
    • 1970-01-01
    • 2019-04-19
    • 1970-01-01
    • 2020-07-25
    • 2022-08-11
    • 2016-01-15
    相关资源
    最近更新 更多