1

I am having trouble with the below switch statement:

names <- rep(1:num.bins, 3)
names <- sort(names)
c.names <- sapply(1:(3*num.bins), function(i){

   switch( i %% 3,
           1 = paste0("M", names[i]),
           2 = paste0("F", names[i]),
           0 = paste0("E", names[i])
            )
    })

If my 'num.bins' is 3, I'd like the following output:

print(names)
[1] 1 1 1 2 2 2 3 3 3

print(c.names)
[1] "M1" "F1" "E1" "M2" "F2" "E2" "M3" "F3" "E3"

however, I'm getting an error. Thank you very much for your help.

yaph
  • 33
  • 6

3 Answers3

5

You're getting an error because you can't use digits like 0 or 1 as names of arguments.

However, there's a simple way to do what you're trying to do without a switch statement:

num.bins <- 3
c.names <- paste0(c("M", "F", "E"), rep(1:num.bins, each = 3))
# [1] "M1" "F1" "E1" "M2" "F2" "E2" "M3" "F3" "E3"
David Robinson
  • 77,383
  • 16
  • 167
  • 187
4

Please read the ?switch help page. If you pass a numeric value as the first parameter, named arguments are ignored (and you cannot have numbers as named arguments anyway). You can convert to character if you really want.

c.names <- sapply(1:(3*num.bins), function(i){
   switch( as.character(i %% 3),
           "1" = paste0("M", names[i]),
           "2" = paste0("F", names[i]),
           "0" = paste0("E", names[i])
            )
    })
MrFlick
  • 195,160
  • 17
  • 277
  • 295
4

You need to decide what version of switch you are using. If you decide to go with the numeric version, then you need to have the indexing start with 1. (A zero index will not succeed.) The numeric version does not use the names strategy but is more like choosing items with "[" or "[[":

names <- rep(1:3, 3)
names <- sort(names)
c.names <- sapply(1:(3*3), function(i){

   print( switch( (i %% 3) +1,
           paste0("M", names[i]),
           paste0("F", names[i]),
           paste0("E", names[i])
            ))
    })

[1] "F1"
[1] "E1"
[1] "M1"
[1] "F2"
[1] "E2"
[1] "M2"
[1] "F3"
[1] "E3"
[1] "M3"

If you want the character version (for which either factor or as.character might be a route to coercing your modulus expression), then you would use the val=expr syntax.

IRTFM
  • 258,963
  • 21
  • 364
  • 487