R中出错:下标超出范围

R中出错:下标超出范围,r,R,所以我试着做一些非常简单的事情。在数据帧上循环并计算一对列之间的最大相关系数 我正试图在R做这件事 我的数据帧已使用fread()读取。 这是我的代码:我在开始时声明了max=-1,a=0和b=0 for(i in 2:1933) { for(j in i+1:1934) { if(is.numeric(data[[i]]) && is.numeric(data[[j]])) { if(isTRUE(sd(d

所以我试着做一些非常简单的事情。在数据帧上循环并计算一对列之间的最大相关系数

我正试图在R做这件事

我的数据帧已使用
fread()读取。

这是我的代码:我在开始时声明了
max=-1,a=0
b=0

for(i in 2:1933)
{
    for(j in i+1:1934)
    {
        if(is.numeric(data[[i]]) && is.numeric(data[[j]]))
        {
            if(isTRUE(sd(data[[i]], na.rm=TRUE) !=0) && isTRUE(sd(data[[j]], na.rm=TRUE) !=0))
            {
                c = cor(data[[i]], data[[j]], use="pairwise.complete.obs")
                if(isTRUE(c>=max))
                {
                    max = c
                    a = i
                    b = j
                }
            }
        }
    }
}
我得到的错误是

Error in .subset2(x, i, exact = exact) : subscript out of bounds
我有1934个专栏,我想不出问题所在。我错过了一些很明显的东西吗?

试试这个:

    drop_list <- NULL

#Guess the first column iS ID Column
feature.names <- names(data)[2:length(names(data)]

for(f in feature.names){
  if(sd(data[[f]], na.rm=TRUE) == 0.0 | is.numeric(data[[f]])==FALSE)
     {
     drop_list <- c(drop_list, f)
  }
}

data <- data[,!(names(data) %in% drop_list)]

corr_data <- cor(data, use="pairwise.complete.obs")


##remove Correlation between same variables
for(i in 1:dim(corr_data)[1]){corr_data[i,i] <- -99 }

#Please try to sort the correlation data.frame accordingly with which function as Howard suggested

drop\u list有一种更简单的方法:
cor(…)
获取一个矩阵(
nr X nc
),然后返回一个新矩阵(
nc X nc
),其中包含每一列与其他每一列的相关系数。剩下的很简单:

library(data.table)   # to simulate fread(...)
set.seed(1)           # for reproducibble example
dt <- as.data.table(matrix(1:50+rnorm(50,sd=5), ncol=5)) # create reproducible example


result <- cor(dt, use="pairwise.complete.obs")       # matrix of correlation coefficients
diag(result) <- NA                                   # set diagonals to NA
max(result, na.rm=TRUE)                              # maximum correlation coefficient
# [1] 0.7165304
which(result==max(result, na.rm=TRUE), arr.ind=TRUE) # location of max
#    row col
# V3   3   2
# V2   2   3
library(data.table)#模拟fread(…)
设定种子(1)#用于可复制的示例

dt应该是
(i+1)
您可以使用
combn
作为替代,
combn(数据,2,函数(x)cor(x[[1]],x[[2]],use=“pairwise.complete.obs”)
我最终意识到我没有正确地清理数据,现在已经完成了。我现在该怎么办?mods最终会解决这个问题吗@铺位