简体   繁体   English

如何使函数参数成为R中向量的元素?

[英]How to make function argument an element from the vector in R?

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.我正在尝试创建一个函数,该函数需要参数 z 作为向量中的元素之一。 The function has two other arguments: n (is.numeric = FALSE), and y (is.numeric = TRUE).该函数还有另外两个参数:n (is.numeric = FALSE) 和 y (is.numeric = TRUE)。

arguments n and y result in output1 and output2;参数 n 和 y 导致 output1 和 output2; z results in output3. z 导致输出 3。 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?我的问题是:如何使 output3 仅在参数 z 是向量 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?有没有办法将 z 参数添加到我的“if”语句中? 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.目前我可以获得我想要的输出,但它适用于任何非数字参数作为 z 而不仅仅是向量的元素。 I'm hoping that I've written this clearly;我希望我已经写清楚了; please let me know if I should elaborate further.请让我知道我是否应该进一步详细说明。 Thank you!谢谢!

If you want to know if a certain value is contained somewhere in a vector, you can use the %in% function.如果您想知道某个值是否包含在某个向量中,您可以使用%in%函数。 Assuming all_z is already defined, you can use something like this.假设all_z已经定义,你可以使用这样的东西。

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
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM