错误消息"条件长度> 1,只使用第一个元素"

时间:2015-05-19 03:15:41

标签: r

在Windows 8上使用R-studio我试图使用if使用1个数字的向量列表来子集矩阵列表。矩阵列表和向量列表具有相同的id。但是当我运行我的代码时,我收到一条错误消息:此外:

Warning message: In if (true_only[id] > 0) { :
the condition has length > 1 and only the first element will be used.

我做错了什么?这是我的代码:

  corr <- function(directory, threshold = 0) {
  directory<- c(getwd())
  id=1:332
  filenames <- list.files(pattern= '*.csv$', full.names = TRUE)
  tables<- lapply(filenames[id], read.csv, header = TRUE)
  complete_tables<- lapply(tables, na.omit, header = TRUE)
  s_n_set<- lapply(complete_tables[id], subset, select = c(sulfate, nitrate))
  s_n_set_vector<- lapply(s_n_set[id], as.matrix)
  true_only<- lapply(s_n_set_vector[id], nrow)
          if(true_only[id] > 0){
  corr<- lapply(s_n_set_vector[id], cor, use="complete.obs")

1 个答案:

答案 0 :(得分:1)

这是一条警告消息,而不是错误消息。

1.警告在 if 的情况下,根据警告 true_only [id] 的长度大于1,即它是一个矢量或列表更多比一个项目

2. if 案例仅检查1个项目,因此它会打印警告,它只会检查第一个项目而不是 true_only [id]中的其余项目]

修改后的代码

corr <- function(directory, threshold = 0) {
directory<- c(getwd())
id=1:332
filenames <- list.files(pattern= '*.csv$', full.names = TRUE)
tables<- lapply(filenames[id], read.csv, header = TRUE)
complete_tables<- lapply(tables, na.omit, header = TRUE)
s_n_set<- lapply(complete_tables[id], subset, select = c(sulfate, nitrate))
s_n_set_vector<- lapply(s_n_set[id], as.matrix)
true_only<- lapply(s_n_set_vector[id], nrow)
corr<-numeric(0)
for (i in range id){

      if(true_only[i] > 0){
      z<-matrix(unlist(s_n_set_vector[i]),ncol=2,byrow=F)
cor<- c(corr, cor(z[,1],z[,2],use="complete.obs"))
}