Home > Enterprise >  What is causing my for/if loop to return 'longer object length is not a multiple of shorter obj
What is causing my for/if loop to return 'longer object length is not a multiple of shorter obj

Time:03-11

I am trying to produce vector (PA) from the conditions of two other vectors. The other vectors are both 1978 elements in length.

The vectors are taken from loading in an excel file and using 'x <- S1L1$PercentageCoverage' and 'y <- S1L1$FoldCount'.

I believe the code should be checking if each element in x is equal to or greater than 1, and if each element in y is equal to or greater than 70. If they both pass this check, it should add the value of the ith element in the x vector to PA. If either fail, it should add 0.

PresenceCollector <- function(x, y){

PA <- c() 
    
  for (i in 1:1978){
    if ((x[i] >= 1) && (y[i] >= 70)){
      PA <- c(PA, x[i])
    } else {
      PA < - c(PA, 0)
    }
  }
}

The PA vector remains 'null' even after running the code, and it returns a warning message saying 'There were 50 or more warnings (use warnings() to see the first 50)'. This returns

1: In PA < -c(PA, 0) :
  longer object length is not a multiple of shorter object length
2: In PA < -c(PA, 0) :
  longer object length is not a multiple of shorter object length
3: In PA < -c(PA, 0) :
  longer object length is not a multiple of shorter object length

and so on until it prints 50

Any help on how to fix this? Thank you!

CodePudding user response:

Here a very short solution:

function(x, y){
    x * (x >= 1 & y >= 70)
}

Pay attention to the parenthesis. In there a boolean value is created, i.e. 1s or 0s, and these are then multiplied with x.

CodePudding user response:

"The vectors are taken from loading in an excel file and using 'x <- S1L1$PercentageCoverage' and 'y <- S1L1$FoldCount'."

It looks like you have S1L1 as a dataframe with PercentageCoverage and FoldCount columns and want to create a new column PA when PercentageCoverage >= 1 and FoldCount>=70, then PA should be PercentageCoverage else 0, correct?

S1L1$PA <- ifelse(S1L1$PercentageCoverage>=1 & S1L1$FoldCount>=70, S1L1$PercentageCoverage, 0)
  • Related