mbeasle2
mbeasle2

Reputation: 163

How to make a function input one of many vectors?

I am creating a function where the input is a color and a number 1:10. I have created a vector for four colors (red, yellow, blue, green) and each has 10 entries. I would like to make it so that entering one of the four colors into the function and a number 1:10 will output that entry. For example:

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

function <- function(x,y) {
}

Where x is the color chosen and y is the item in that number position. How can I make it so that entry x has to be one of the color vectors? Do I need to create a separate vector for the colors?

Thank you so much for your help! Let me know if I need to add more clarification.

Upvotes: 0

Views: 84

Answers (2)

Gregor Thomas
Gregor Thomas

Reputation: 146030

You don't need a function, you just need a list:

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

You can use $ with a name or [[ with a string to access the items of the list, and [ to get individual sub-items.

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"

How can I make it so that entry x has to be one of the color vectors?

Colors that aren't in the list won't work:

my_cols[["chartreuse"]]
# NULL

But if you want, say, custom error messages, then we can wrap it up in a function:

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

If this is in a shiny app or something, then it would be reasonable to set col_list = my_cols as a default for the function so you don't need to pass it in every time.

Upvotes: 1

Duck
Duck

Reputation: 39613

Maybe this:

#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)

Output:

[1] "item3"

Upvotes: 1

Related Questions