R Statements (If, Loop, Etc.)
R Statements (If, Loop, Etc.)
Similar to any programming language, R also provides statements like if, loop,
while, and repeat e.t.c
The R language supports three different ways to write if else statement , The if,
if…else, and if…else…if in R. These if statements are conditional decision-
making statements that are used to execute a block of code based on a
condition.
Following are some examples of an if statement with a condition. You can also
write R if..else with multiple conditions .
# R if statement
str <- 'Spark'
if(str == 'Spark') {
print('IF CONDITION IS TRUE')
}
# R if...else statement
str <- 'Python'
if(str == 'Spark') {
print('IF CONDITION IS TRUE')
}else{
print('IF CONDITION IS FALSE')
}
# R if...else if
str <- 'Python'
if(str == 'Spark') {
print('str value is Spark')
}else if(str == 'Python' ) {
print('str value is Python')
}else{
print('str value is not Spark and Python')
}
Alternatively, you can also use ifelse() function from the R base package that
takes a vector as input and return a vectorized output. The ifelse() is a function
that takes a vector as a test condition and executes the test condition for each
element in th
5.2 for loop
Open your preferred text editor and create a file named helloworld.r. Include
the data frame and print statements as described in section 2.
R script file
Now, open the terminal or command prompt and run the R script file using
the rscript command. If the file is stored in a custom location, use the absolute
path of the script to execute it. You can also create an R program in RStudio,
save the file to the disk, and run it using the rscript command.
In this R Programming Tutorial, you have learned what is R, its usage, and how
to install and run the Hello World program. Also, it learned data structures it
supports like Vector, Matrix, and Data Frame. Finally looked into different R
packages.