jeudi 27 juin 2019

Error creating a vector from a self-made function

Trying to make my problem reproducible, I have the following vector:

trialvector <- as.vector(c("K", "K", "m", "m", "K"))

And this function to try to convert this vector into one which transforms "K" into a numeric 3 and "m" into a numeric 6, I want to assign this vector to a variable called multiplier:

 Expcalc <- function(vector)  {
 multiplier <<- vector(mode = "numeric", length = length(vector))
 for (i in seq_along(vector)) {
   if (vector[i] == "K") {
     multiplier[i] <- 3
   } else if (vector[i] == "M" | i == "m") {
     multiplier[i] <- 6
   } else {
     multiplier[i] <- 0
   }
 }
}

Instead of getting the output I want (a Vector of 6 and/or 3 depending on which character was in trialvector, I get a vector full of zeros. and this error:

Warning messages: 1: In Expcalc(trialvector) : NAs introduced by coercion 2: In Expcalc(trialvector) : NAs introduced by coercion

What am I doing wrong?

Aucun commentaire:

Enregistrer un commentaire