1
votes

I have a vector of non-numeric elements:

all_z <- c("red","yellow","blue")

And I am trying to make a function that requires argument z to be one of the elements in the vector. The function has two other arguments: n (is.numeric = FALSE), and y (is.numeric = TRUE).

arguments n and y result in output1 and output2; z results in output3. Currently my code looks like this (verb and noun are previously defined vectors):

byColor <- function(n,y,z) {
  if ((is.numeric(n) == FALSE) && (is.numeric(y) == TRUE)){
  output1 <- sample(verb, 1, replace = FALSE)
  output2 <- sample(noun, 1)
 }
}

My question is: how do I make it so that output3 occurs only if argument z is an element from the vector all_z? My end goal is stringing all three outputs together, but only if all three of these arguments are satisfied. Is there a way to add the z argument into my "if" statement? Currently I can get the output that I want, but it works for any non-numerical argument as z and not just elements of the vector. I'm hoping that I've written this clearly; please let me know if I should elaborate further. Thank you!

1
if(z %in% all_z) {output <- something}? your question is not clear to me. Can you call the function on actual data and edit your question? The second { in byColor function shouldn't be there.Liman

1 Answers

1
votes

If you want to know if a certain value is contained somewhere in a vector, you can use the %in% function. Assuming all_z is already defined, you can use something like this.

byColor <- function(n, y, z) {
    if ((is.numeric(n) == FALSE) &&
            (is.numeric(y) == TRUE) && 
            (z %in% all_z)) {
                output1 <- sample(verb, 1, replace = FALSE)
                output2 <- sample(noun, 1)
                output3 <- NULL
    }
}