1

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. Commented Sep 7, 2020 at 15:17

1 Answer 1

1

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 } } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.