你不需要一个函数,你只需要一个列表:
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 设置为函数的默认值是合理的,这样您就不需要每次都传递它。