【问题标题】:How to make a function input one of many vectors?如何使函数输入多个向量之一?
【发布时间】:2021-01-23 18:13:18
【问题描述】:

我正在创建一个函数,其中输入是颜色和数字 1:10。我为四种颜色(红色、黄色、蓝色、绿色)创建了一个矢量,每种颜色都有 10 个条目。我想这样做,以便在函数中输入四种颜色中的一种,并且数字 1:10 将输出该条目。例如:

red <- c("item1", "item2", "item3")
yellow <- c("item1", "item2", "item3")
blue <- c("item1", "item2", "item3")
green <- c("item1", "item2", "item3")

function <- function(x,y) {
}

其中 x 是选择的颜色,y 是该数字位置的项目。我怎样才能使条目 x 必须是颜色向量之一?我需要为颜色创建一个单独的矢量吗?

非常感谢您的帮助!让我知道是否需要添加更多说明。

【问题讨论】:

    标签: r function vector subset


    【解决方案1】:

    也许是这样的:

    #Data
    red <- c("item1", "item2", "item3")
    yellow <- c("item1", "item2", "item3")
    blue <- c("item1", "item2", "item3")
    green <- c("item1", "item2", "item3")
    #Function
    myfunction <- function(x,y)
    {
      x[y]
    }
    #Apply
    myfunction(x=red,y=3)
    

    输出:

    [1] "item3"
    

    【讨论】:

    • 我很困惑 OP 似乎更喜欢 myfunction(red, 3) 而不是 red[3]...
    • @GregorThomas 嗨,格雷戈尔先生!也许他正在处理一个大函数,需要使用函数打包输出或定义函数,以便您插入一个值并返回项目。我知道这就是观点。
    【解决方案2】:

    你不需要一个函数,你只需要一个列表:

    my_cols = list(
      red = c("item1", "item2", "item3"),
      yellow = c("item1", "item2", "item3"),
      blue = c("item1", "item2", "item3"),
      green = c("item1", "item2", "item3")
    )
    

    您可以使用带有名称的$ 或带有字符串的[[ 来访问列表中的项目,并使用[ 来获取各个子项目。

    my_cols$red
    # [1] "item1" "item2" "item3"
    
    my_cols[["red"]]
    # [1] "item1" "item2" "item3"
    
    my_cols$red[2]
    # [1] "item2"
    
    my_cols[["red"]][2]
    # [1] "item2"
    

    我怎样才能使条目 x 必须是颜色向量之一?

    不在列表中的颜色将不起作用:

    my_cols[["chartreuse"]]
    # NULL
    

    但是,如果您想要自定义错误消息,那么我们可以将其包装在一个函数中:

    col_item_picker = function(color, item, col_list) {
      if(!color %in% names(my_cols)) stop("Invalid color choice!")
      if(item > length(my_cols[[color]])) stop(sprintf("%s only has %s items", color, length(my_cols[[color]])))
      col_list[[color]][item]
    }
    
    col_item_picker("red", 2, my_cols)
    # [1] "item2"
    col_item_picker("chartreuse", 2, my_cols)
    # Error in col_item_picker("chartreuse", 2, my_cols) : 
    #   Invalid color choice!
    col_item_picker("red", 101, my_cols)
    # Error in col_item_picker("red", 101, my_cols) : red only has 3 items
    

    如果这是在闪亮的应用程序或其他东西中,那么将 col_list = my_cols 设置为函数的默认值是合理的,这样您就不需要每次都传递它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-12
      • 2013-06-01
      相关资源
      最近更新 更多