brueggel
brueggel

Reputation: 21

error message "the condition has length > 1 and only the first element will be used"

Using R-studio on Windows 8 I am trying to use if to subset list of matrices using list of vectors with 1 number. Both list of matrices and list of vectors have same id. But when I run my code I am getting an error message: In addition:

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

What am I doing wrong? Here is my code:

  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")

Upvotes: 2

Views: 6616

Answers (1)

The6thSense
The6thSense

Reputation: 8335

It is a warning message and not a error message .

1.The warning is in the if case and according to the warning true_only[id] has length greater than 1 that is it is a vector or list with more than one item

2.The if case only checks for only 1 item and therefore it is printing the warning that it will check with only the first item and not with the remaining items in true_only[id]

Modified code

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"))
}

Upvotes: 1

Related Questions