0% found this document useful (0 votes)
18 views36 pages

Control Structures in R

The document provides an overview of control structures and input methods in R programming. It explains how to take user input using the readline() and scan() methods, including converting data types and handling multiple inputs. Additionally, it covers various control structures such as if-else statements, loops, and the switch statement for decision-making in R.

Uploaded by

ansarisshadan748
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views36 pages

Control Structures in R

The document provides an overview of control structures and input methods in R programming. It explains how to take user input using the readline() and scan() methods, including converting data types and handling multiple inputs. Additionally, it covers various control structures such as if-else statements, loops, and the switch statement for decision-making in R.

Uploaded by

ansarisshadan748
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 36

Control

Structures in R
Dr. Rakhee Chhibber
Taking input in R
There are two methods in R.

• Using readline() method


• Using scan() method
Using readline() method
In R language readline() method takes input in string format. If
one inputs an integer then it is inputted as a string, lets say, one
wants to input 255, then it will input as “255”, like a string. So one
needs to convert that inputted value to the format that he needs. In
this case, string “255” is converted to integer 255. To convert the
inputted value to the desired data type, there are some functions in
R,

• as.integer(n); —> convert to integer


• as.numeric(n); —> convert to numeric type (float, double etc)
• as.complex(n); —> convert to complex number (i.e 3+2i)
• as.Date(n) —> convert to date …, etc
Reading input through
keyboard # R program to illustrate
# taking input from the user

# taking input using readline()


# this command will prompt you
# to input a desired value
var = readline();

# convert the inputted value to integer


var = as.integer(var);

# print the value


print(var)
Prompt a message
One can also show message in the console window to tell the user,
what to input in the program. To do this one must use a argument
named prompt inside the readline() function.
Actually prompt argument facilitates other functions to
constructing of files documenting. But prompt is not mandatory to
use all the time.
# R program to illustrate
# taking input from the user
# taking input with showing the message
var = readline(prompt = "Enter any number : ");
# convert the inputted value to an integer
var = as.integer(var);
# print the value
print(var)
multiple inputs in R
# R program to illustrate
# taking multiple inputs
# using braces
{
var1 = readline("Enter 1st number : ");
var2 = readline("Enter 2nd number : ");
var3 = readline("Enter 3rd number : ");
var4 = readline("Enter 4th number : ");
}
# converting each value
var1 = as.integer(var1);
var2 = as.integer(var2);
var3 = as.integer(var3);
var4 = as.integer(var4);

# print the sum of the 4 number


print(var1 + var2 + var3 + var4)
String and Character input in
R
For “String” one doesn’t need to convert the inputted data into a string because
R takes input as string always. And for “character”, it needs to be converted to
‘character’. Sometimes it may not cause any error. One can take character input
as same as string also, but that inputted data is of type string for the entire
program. So the best way to use that inputted data as ‘character’ is to convert
the data to a character.
# R program to illustrate
# taking input from the user

# string input
var1 = readline(prompt = "Enter your name : ");

# character input
var2 = readline(prompt = "Enter any character : ");
# convert to character
var2 = as.character(var2)

# printing values
print(var1)
print(var2)
Using scan() method
Another way to take user input in R language is using a method,
called scan() method. This method takes input from the console.
This method is a very handy method while inputs are needed to
taken quickly for any mathematical calculation or for any dataset.
This method reads data in the form of a vector or list. This method
also uses to reads input from a file also.
# R program to illustrate
# taking input from the user

# taking input using scan()


x = scan()
# print the inputted values
print(x)

Explanation:
Total 12 integers are taking as input in 2 lines when the
control goes to 3rd line then by pressing Enter key 2 times
the input process will be terminated.
double, string, character type
values using scan() method
To take double, string, character types inputs, specify the type of the
inputted value in the scan() method. To do this there is an argument
called what, by which one can specify the data type of the inputted
value.
# R program to illustrate
# taking input from the user

# double input using scan()


d = scan(what = double())

# string input using 'scan()'


s = scan(what = " ")

# character input using 'scan()'


c = scan(what = character())

# print the inputted values


print(d) # double
print(s) # string
print(c) # character
Read File data using scan()
method
To read file using scan() method is same as normal console input,
only thing is that, one needs to pass the file name and data type to
the scan() method.
# R program to illustrate
# taking input from the user

# string file input using scan()


s = scan("fileString.txt", what = " ")

# double file input using scan()


d = scan("fileDouble.txt", what = double())

# character file input using scan()


c = scan("fileChar.txt", what = character())

# print the inputted values


print(s) # string
print(d) # double
print(c) # character
Print statement in R
Print without print function
# select 'x' and then press 'run' button
# it will print 'GeeksforGeeks' on the console
x <- "GeeksforGeeks"
x
Print output
using print() function
# R program to illustrate
# printing output of an R program print string
print("GFG")
# print variable
# it will print 'GeeksforGeeks' on the console
x <- "GeeksforGeeks"
print(x)
Print output using paste() function
inside print() function
R provides a method paste() to print output with string and variable
together. This method defined inside the print() function. paste() converts
its arguments to character strings. One can also use paste0() method.

Note: The difference between paste() and paste0() is that the


argument sep by default is ” “(paste) and “”(paste0).
# R program to illustrate
# printing output of an R program

x <- "GeeksforGeeks"

# using paste inside print()


print(paste(x, "is best (paste inside print())"))

# using paste0 inside print()


print(paste0(x, "is best (paste0 inside print())"))
Print output
using sprintf() function
sprintf() is basically a C library function. This function is use to print string as C
language. This is working as a wrapper function to print values and strings
together like C language. This function returns a character vector containing a
formatted combination of string and variable to be printed.
# R program to illustrate
# printing output of an R program

x = "GeeksforGeeks" # string
x1 = 255 # integer
x2 = 23.14 # float

# string print
sprintf("%s is best", x)

# integer print
sprintf("%d is integer", x1)

# float print
sprintf("%f is float", x2)
Print output
using cat() function
Another way to print output in R is using of cat() function. It’s same
as print() function. cat() converts its arguments to character
strings. This is useful for printing output in user defined functions.

# R program to illustrate
# printing output of an R program
# print string with variable
# "\n" for new line
x = "GeeksforGeeks"
cat(x, "is best\n")
# print normal string
cat("This is R language")
Introduction
Control Structures are an integral part of any programming language. We can say
that a programming language without control structures is incomplete. These
control structures are basically a block of code lines that decide which direction
to go once the executed and often called as well as considered as loops. Control
structures are mostly used for decision making.
• If – else statement
• ifelse() function
• Switch Statement
• for loop
• while loop
• Break Statement
• Next Statement
• Report Loops
If..condition

x <- 100

if(x > 10){


print(paste(x, "is greater than 10"))
}
If..else condition

x <- 5

# Check value is less than or greater than 10


if(x > 10){
print(paste(x, "is greater than 10"))
}else{
print(paste(x, "is less than 10"))
}
For loop

x <- letters[4:10]

for(i in x){
print(i)
}
Nested loops
# Defining matrix
m <- matrix(2:15, 2)

for (r in seq(nrow(m))) {
for (c in seq(ncol(m))) {
print(m[r, c])
}
}
While loop
x=1

# Print 1 to 5
while(x <= 5){
print(x)
x=x+1
}
repeat loop and break
statement
repeat is a loop which can be iterated many number of times but
there is no exit condition to come out from the loop. So, break
statement is used to exit from the loop. break statement can be
used in any type of loop to exit from the loop.
x=1

# Print 1 to 5
repeat{
print(x)
x=x+1
if(x > 5){
break
}
}
return statement
# Checks value is either positive, negative or
return statement is used zero
to return the result of an func <- function(x){
executed function and if(x > 0){
returns control to the return("Positive")
calling function. }else if(x < 0){
return("Negative")
}else{
return("Zero")
}}
#Function calling
func(1)
func(0)
func(-1)
next statement
next statement is used to skip # Defining vector
the current iteration without x <- 1:10
executing the further
statements and continues the # Print even numbers
next iteration cycle without for(i in x){
terminating the loop. if(i%%2 != 0){
next #Jumps to next loop
}
print(i)
}
Switch case

Important Points about Switch Case Statements:


•An expression type with character string always matched to the listed
cases.
•An expression which is not a character string then this exp is coerced
to integer.
•For multiple matches, the first match element will be used.
•No default argument case is available there in R switch case.
•An unnamed case can be used, if there is no matched case.
# Following is val1 simple R program
# to demonstrate syntax of switch.
# Mathematical calculation

val1 = 6
val2 = 7
val3 = "s"
result = switch(
val3,
"a"= cat("Addition =", val1 + val2),
"d"= cat("Subtraction =", val1 - val2),
"r"= cat("Division = ", val1 / val2),
"s"= cat("Multiplication =", val1 * val2),
"m"= cat("Modulus =", val1 %% val2),
"p"= cat("Power =", val1 ^ val2)
)
print(result)

You might also like