2

Google search doesn't return much on this. How do you unpack arguments in R?

For instance if I try to use switch in R like

switch("AA",c("AA"=5,"BB"=6))

I will get back c("AA"=5,"BB"=6) when in reality, I want 5.

Essentially, I want to be able to do switch("AA","AA"=5,"BB"=6) with a vector mapping.

user1431282
  • 6,535
  • 13
  • 51
  • 68

4 Answers4

3

This is a bit of a workaround, but try:

do.call("switch", append(list("AA"), list("AA"=5, "BB"=6)))

The do.call() allows you to pass a list of arguments into switch().

  • +1 - or `do.call(switch, as.list(c(EXPR = "AA", c("AA"= 5,"BB"= 6))))` – flodel Mar 26 '13 at 00:54
  • Couldn't this be simplified to `do.call("switch", append("AA", list("AA"=5, "BB"=6)))`. What does the `list("AA")` do? – Thomas May 08 '13 at 20:08
  • @Thomas It can be shortened as you suggest. The `list("AA")` was to insure that there wasn't any type coercion to go wrong. Your shortened version is converting a one element character vector to a one element list before appending the other list. –  May 08 '13 at 20:25
3

This is how switch was intended to be used. The first argument gets evaluated and match to the first elements of the succeeding pairlists:

 aa <- "AA"
 switch(aa,"AA"=5,"BB"=6)
#[1] 5
 switch("BB","AA"=5,"BB"=6)
#[1] 6

At least that is the strategy for 'character' arguments. The process for numeric arguments is different. One needs to read the Details section of ?switch carefully.

IRTFM
  • 258,963
  • 21
  • 364
  • 487
2

Your example is rather short, mayby you could obtain demanded functionality this way :

my.vector = c("AA"=5,"BB"=6)
my.vector[names(my.vector ) == "AA"]

AA 
 5 

?

Qbik
  • 5,885
  • 14
  • 62
  • 93
2
> c("AA"=5,"BB"=6)["AA"]
AA 
 5 
> c("AA"=5,"BB"=6)["BB"]
BB 
 6 
Julián Urbano
  • 8,378
  • 1
  • 30
  • 52