R Switch | R Switch Functions - r - learn r - r programming



  • In R, switch statement evaluates equality of an variable or expression against multiple case values in order to evaluate the block of code to be executed.
  • The switch takes an expression and returns a value in a list built on the value of the expression which depends on the data type of the expression.
  • In switch expression values is tested against multiple case values (case1, case2, case3..., caseN)
switch case stetement

Syntax

switch (statement, list)

Syntax Explanation:

  • statement:The statement is assessed based on this value and the result.
  • list: The equivalent item in the list is returned, if the value is a number between 1 and the length of list. If the value is too large or too small, then NULL is returned.

Sample Code

switch(3,"Mango","Apple","Guava")


switch(1,"Mango","Apple","Guava")


n <- switch(0,"Mango","Apple","Guava")
n


n<- switch(4,"Mango","Apple","Guava")
n


switch("color", "fruit"="Mango", "color"="Yellow", "price"=50)


switch("price", "fruit"="Mango", "color"="Yellow", "price"=50)

Code Explanation

 r switch functions strcture
  1. There are three of list items "Mango", "Apple", "Guava". The switch() function returns the corresponding item to the numeric value 3.
  2. The switch() function returns the corresponding item to the numeric value 1 is then assessed.
  3. Next we create a three of list items "Mango", "Apple", "Guava". Here the switch() function returns the corresponding item to the numeric value 0 and is evaluated.
  4. By the same way, the switch() function returns the corresponding item to the numeric value 4 is evaluated.
  5. Here, represented a “color” string which means the matching named item's value is returned.
  6. This statement can be denoted as a “price” string that means the matching named item's value is displayed.

Output

 r switch functions output
  1. In this output "Guava","Mango" is a list of items. Therefore, the switch() function returns the selected numeric values 3 & 1 evaluated.
  2. Here, the numeric value is out of range, which means 4 is greater than the number of items in the list and 0 is smaller than 1, then, output prints NULL as a return value.
  3. In this statement can be represented as "color" and “price” strings, which means the matching named item's “yellow” and “50” values are returned as output.

Related Searches to R Switch | R Switch Functions