Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in R Programming by (5.3k points)

I am a little confused about the switch statement in R. Simply googling the function I get an example as follows:

A common use of switch is to branch according to the character value of one of the arguments to a function.

 > centre <- function(x, type) {

 + switch(type,

 +        mean = mean(x),

 +        median = median(x),

 +        trimmed = mean(x, trim = .1))

 + }

 > x <- rcauchy(10)

 > centre(x, "mean")

 [1] 0.8760325

 > centre(x, "median")

 [1] 0.5360891

 > centre(x, "trimmed")

 [1] 0.6086504

However, this just seems to be the same as just having a bunch of if statements designated for each type

Is that all there is to switch()? Can someone give me further examples and better applications?

1 Answer

0 votes
by

A switch() statement is generally faster than the if() statement and the code in a switch() statement is shorter and neater as compared to the if() statement.

For example:

test1 <- function(type) {

  switch(type,

         mean = 1,

         median = 2,

         trimmed = 3)

}

test2 <- function(type) {

  if (type == "mean") 1

  else if (type == "median") 2

  else if (type == "trimmed") 3

}

Microbenchmarks in Nanoseconds:

library(microbenchmark)

> microbenchmark(test1('mean'), test2('mean'), times=1e5)

Unit: nanoseconds

          expr min  lq    mean median  uq   max neval cld

 test1("mean") 200 200 274.219    300 300 33000 1e+05  a 

 test2("mean") 300 300 361.164    300 400 44000 1e+05   b

microbenchmark(test1('trimmed'), test2('trimmed'), times=1e6)

Unit: nanoseconds

             expr min  lq     mean median  uq      max neval cld

 test1("trimmed") 200 300 346.4554    300 300    93700 1e+06  a 

 test2("trimmed") 500 500 679.5067    600 600 11110100 1e+06   b

Related questions

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...