mercredi 5 février 2020

How to write a function containing a 'for' loop that uses a different function within? Applying this function to vectors?

I think I am misunderstanding some fundamental part of how 'for' loops and functions work. This function:

  even.odd <- function(x) {
  if (x != round(x)) {
    y <- NA
  } else if (x %% 2 == 0) {
    y <- "even"
  } else {
    y <- "odd"
  } 
  return(y)
}

works perfectly fine, returning "even", "odd", or "NA" given a number. However I am given two vectors :

test1 <- c(-1, 0, 2, 5)
test2 <- c(0, 2.7, 9.1)

and need to create a 'for' loop containing the even.odd function and test it using these vectors. I have read all the recommended reading/lecture notes, and tried for hours unsuccessfully to produce the desired result, using empty vectors, indexing new objects, just putting even.odd(num.vec). I'm not sure where I've gone so wrong.

We were given a starting point for the new function:

even.odd.vec <- function(num.vec) {
#write your code here 
}

So far this is what I have come up with:

  #creating intermediate function 
intermediate <- function(num.vec) {
      if (even.odd(num.vec) == "odd") {
        return("odd")
      } else if(even.odd(num.vec) == "even") {
        return("even")
      } else ifelse(is.na(num.vec), NA, "False")
    }

#creating new desired function
    even.odd.vec <- function(num.vec) {
      for (i in seq_along(num.vec)) {
       intermediate(num.vec)
      print(intermediate(num.vec))
      }
    }

The intermediate function was the result of me running into various errors when trying to create a simpler body for even.odd.vec. But now when I try to use even.odd.vec with one of the test vectors I get this error:

the condition has length > 1 and only the first element will be usedthe condition has length > 1 and only the first element will be usedthe condition has length > 1 and only the first element will be usedthe condition has length > 1 and only the first element will be used

I am very stuck at this point and dying to know how to make something like this work. I've had a lot of fun working on it but I think I'm digging myself into a hole and/or making things much more complicated than necessary. Any help is unbelievably appreciated as my professor is out of town and the TA seems overwhelmed.

Aucun commentaire:

Enregistrer un commentaire