findCorrelation(插入符包)的输出不正确
Incorrect output of findCorrelation (caret package)
我使用 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
但是,如果我应用截止值=0.1,例如,我将得到一个零矩阵,而不是截止值以下所有因子的列表:
hc <- findCorrelation(as.matrix(df2), cutoff=0.1)
hc <- sort(hc)
print(df2[-hc,-hc])
cutoff=0.1 的 df2 输出:
<0 x 0 matrix>
我的业务案例中有 运行 个其他示例,似乎至少有一个因子高于临界值以生成低于临界值的因子矩阵。
否则,生成零矩阵。
我已经研究了 'findCorrelation' 的脚本,但效果很好。也许脚本不被假定为处理这种情况。
因此,如果您能提供解决该问题的提示,我将不胜感激。
2016 年 7 月 3 日更新:
由于@topepo 的有用回答,我修改了脚本:
要替换的部分:
print(df2[-hc,-hc])
与:
if(length(hc)==0){
print(df2)
}else{
print(df2[-hc,-hc])
}
这不是错误。
在?findCorrelation
中,将返回值描述为
A vector of indices denoting the columns to remove (when names = TRUE
) otherwise a vector of column names. If no correlations meet the criteria, integer(0)
is returned.
你看到结果的问题是因为你需要通过类似
的方式确保子集向量有它的元素
if(length(hc) > 0) df2 <- df2[-hc, -hc]
任何零长度整数都会产生此问题。
我使用 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
但是,如果我应用截止值=0.1,例如,我将得到一个零矩阵,而不是截止值以下所有因子的列表:
hc <- findCorrelation(as.matrix(df2), cutoff=0.1)
hc <- sort(hc)
print(df2[-hc,-hc])
cutoff=0.1 的 df2 输出:
<0 x 0 matrix>
我的业务案例中有 运行 个其他示例,似乎至少有一个因子高于临界值以生成低于临界值的因子矩阵。
否则,生成零矩阵。
我已经研究了 'findCorrelation' 的脚本,但效果很好。也许脚本不被假定为处理这种情况。
因此,如果您能提供解决该问题的提示,我将不胜感激。
2016 年 7 月 3 日更新:
由于@topepo 的有用回答,我修改了脚本:
要替换的部分:
print(df2[-hc,-hc])
与:
if(length(hc)==0){
print(df2)
}else{
print(df2[-hc,-hc])
}
这不是错误。
在?findCorrelation
中,将返回值描述为
A vector of indices denoting the columns to remove (when
names = TRUE
) otherwise a vector of column names. If no correlations meet the criteria,integer(0)
is returned.
你看到结果的问题是因为你需要通过类似
的方式确保子集向量有它的元素
if(length(hc) > 0) df2 <- df2[-hc, -hc]
任何零长度整数都会产生此问题。