Professional Documents
Culture Documents
Learn R Programming - GeeksforGeeks
Learn R Programming - GeeksforGeeks
Learn R Programming - GeeksforGeeks
Learn R Programming
Read Discuss Courses Practice
Applications of R
Hello World in R
R Program can be run in several ways. You can choose any of the
following options to continue with this tutorial.
Now type the below code to print hello world on your console.
# R Program to print
# Hello World
print("HelloWorld")
Output:
[1] "HelloWorld"
Fundamentals of R
Variables:
variable_name = value
Example:
# R program to illustrate
# Initialization of variables
Output:
[1] "gfg"
[1] "gfg"
[1] "gfg"
Comments:
Comments are the english sentences that are used to add useful
information to the source code to make it more understandable by the
reader. It explains the logic part used in the code and will have no
impact in the code during its execution. Any statement starting with
“#” is a comment in R.
Example:
# Printing sum
print(a + b)
Output:
[1] 3
Operators
Operators are the symbols directing the various kinds of operations
that can be performed between the operands. Operators simulate the
various mathematical, logical and decision operations performed on a
set of Complex Numbers, Integers, and Numericals as input operands.
These are classified based on their functionality –
Example:
# R program to illustrate
# the use of Arithmetic operators
a <- 12
b <- 5
Output:
Addition : 17
Subtraction : 7
Multiplication : 60
Division : 2.4
Modulo : 2
Power operator : 248832
Example:
# R program to illustrate
# the use of Logical operators
vec1 <- c(FALSE, TRUE)
vec2 <- c(TRUE,FALSE)
Output:
Example:
# R program to illustrate
# the use of Relational operators
a <- 10
b <- 14
Output:
Example:
# R program to illustrate
# the use of Assignment operators
Output:
Value 1 : GeeksForGeeks
Value 2 : GeeksForGeeks
Value 3 : GeeksForGeeks
Value 4 : GeeksForGeeks
Value 5 : GeeksForGeeks
Keywords:
for TRUE NA …
Data Types
Each variable in R has an associated data type. Each data type requires
different amounts of memory and has some specific operations which
can be performed over it. R supports 5 type of data types. These are –
Data Example Description
Types
TRUE,
Logical Take either a value of true or false
FALSE
‘a’, ’12’,
R supports character data types where you
Character “GFG”,
have all the alphabets and special characters.
”’hello”’
Example:
# A simple R program
# to illustrate data type
print("Numberic type")
# Assign a decimal value to x
x = 12.25
print("----------------------------")
print("Logical Type")
# Sample values
x = 1
y = 2
print("----------------------------")
print("Complex Type")
# Assign a complex value to x
x = 12 + 13i
print("----------------------------")
print("Character Type")
Output:
Basics of Input/Output
Example:
# R program to illustrate
# taking input from the user
Example:
# R program to illustrate
# taking input from the user
# R program to illustrate
# printing output of an R program
# print string
print("Hello")
# print variable
# it will print 'GeeksforGeeks' on
# the console
x <- "Welcome to GeeksforGeeks"
print(x)
Output:
[1] "Hello"
[1] "Welcome to GeeksforGeeks"
Example:
# R program to illustrate
# printing output of an R
# program
Hello
welcome
to GeeksForGeeks
Decision Making
Decision making decides the flow of the execution of the program
based on certain conditions. In decision making programmer needs to
provide some condition which is evaluated by the program, along with
it there also provided some statements which are executed if the
condition is true and optionally other statements if the condition is
evaluated to be false.
if statement
if-else statement
if-else-if ladder
nested if-else statement
switch statement
# R program to illustrate
# decision making
a <- 99
b <- 12
Output:
# R program to demonstrate
# decision making
a <- 10
# is-elif
if (a == 11)
{
print ("a is 11")
} else if (a==10)
{
print ("a is 10")
} else
print ("a is not present")
z <- switch(
"GfG", # Expression
"GfG0"="Welcome", # case 1
"GfG1"="to", # case 2
"GfG3"="GFG" # case 3
)
print(z)
Output:
[1] "to"
[1] "GFG"
NULL
Note: For more information, refer Decision Making in R Programming
Control Flow
Loops are used wherever we have to execute a block of statements
repeatedly. For example, printing “hello world” 10 times. The different
types of loops in R are –
For Loop
Example:
Output:
[1] -8
[1] 9
[1] 11
[1] 45
While Loop
Example:
val = 1
Output:
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
Repeat Loop
Example:
val = 1
Output:
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
print("------------------------------------")
Output:
Functions
Functions are the block of code that given the user the ability to reuse
the same code which saves the excessive use of memory and provides
better readability to the code. So basically, a function is a collection of
statements that perform some specific task and return the result to the
caller. Functions are created in R by using the command function()
keyword
Example:
# A simple R program to
# demonstrate functions
ask_user = function(x){
print("GeeksforGeeks")
}
my_func = function(x){
a <- 1:5
b <- 0
for (i in a){
b = b +1
}
return(b)
}
ask_user()
res = my_func()
print(res)
Output:
[1] "GeeksforGeeks"
[1] 5
Example:
evenOdd = function(x){
if(x %% 2 == 0)
# Function definition
# To check a is divisible by b or not
divisible <- function(a, b){
if(a %% b == 0)
{
cat(a, "is divisible by", b, "\n")
} else
{
cat(a, "is not divisible by", b, "\n")
}
}
Output:
[1] "even"
[1] "odd"
7 is not divisible by 3
36 is divisible by 6
9 is not divisible by 2
Example:
Output:
20 is divisible by 2
12 is not divisible by 9
Example:
# Function call
fun(5, 1L, 6i, TRUE, "GFG", 1:2)
Output:
Functions in R Programming
Function Arguments in R Programming
Types of Functions in R Programming
Data Structures
A data structure is a particular way of organizing data in a computer so
that it can be used effectively.
Vectors:
Vectors in R are the same as the arrays in C language which are used
to hold multiple data values of the same type. One major key point is
that in R the indexing of the vector will start from ‘1’ and not from ‘0’.
Example:
# Numeric Vector
N = c(1, 3, 5, 7, 8)
# Character vector
C = c('Geeks', 'For', 'Geeks')
# Logical Vector
L = c(TRUE, FALSE, FALSE, TRUE)
# Printing vectors
print(N)
print(C)
print(L)
Output:
[1] 1 3 5 7 8
[1] "Geeks" "For" "Geeks"
[1] TRUE FALSE FALSE TRUE
There are many ways through which we can access the elements of
the vector. The most common is using the ‘[]’, symbol.
Example:
# Logical indexing
Z <- c(1, 6, 9, 4, 6)
print('Logical indexing')
print(Z[Z>3])
Output:
R – Vector
Types of Vectors in R Programming
Operations on Vectors in R
Lists:
Example:
print(empList)
Output:
[[1]]
[1] 1 2 3 4
[[2]]
[1] "Nisha" "Nikhil" "Akshu" "Sambha"
[[3]]
[1] 4
[[4]]
[1] "GFG"
Example:
# R program to access
# components of a list
Output:
$Names
[1] "Nisha" "Nikhil" "Akshu" "Sambha"
$`Total Staff`
[1] 4
Example:
# R program to access
# components of a list
cat("\nAfter modification\n")
print(empList)
Output:
$`Total Staff`
[1] 4
$Names
[1] "Nisha" "Nikhil" "Akshu" "Sambha"
$`Total Staff`
[1] 4
$organization
[1] "GFG"
After modification
$ID
[1] 1 2 3 4 7
$Names
[1] "Nisha" "Nikhil" "Akshu" "Sambha"
$`Total Staff`
[1] 5
$organization
[1] "GFG"
Matrices:
Example:
A = matrix(
# Taking sequence of elements
c(1, 4, 5, 6, 3, 8),
print(A)
Output:
Example:
# R program to illustrate
# access rows in metrics
print(A[1, 1])
print(A[2, 2])
Output:
Example:
# R program to illustrate
# editing elements in metrics
Output:
R – Matrices
Operations on Matrices in R
Algebraic Operations on a Matrix in R
Matrix Transpose in R
Inverse of Matrix in R
DataFrame:
Dataframes are generic data objects of R which are used to store the
tabular data. They are two-dimensional, heterogeneous data
structures. These are lists of vectors of equal lengths.
Example:
print(df)
Output:
One can get the structure of the data frame using str() function.
One can extract a specific column from a data frame using its
column name.
Example:
Output:
'data.frame': 5 obs. of 2 variables:
$ friend_id : int 1 2 3 4 5
$ friend_name: chr "Aman" "Nisha" "Nikhil" "Raju" ...
NULL
friend.data.friend_name
1 Aman
2 Nisha
3 Nikhil
4 Raju
5 Raj
Summary of dataframe:
Example:
Output:
friend_id friend_name
Min. :1 Length:5
1st Qu.:2 Class :character
Median :3 Mode :character
Mean :3
3rd Qu.:4
Max. :5
R – Data Frames
DataFrame Operations
DataFrame Manipulation
Joining of Dataframes
Data Reshaping
Handling Missing Values
Arrays:
Arrays are the R data objects which store the data in more than two
dimensions. Arrays are n-dimensional data structures.
Example:
A = array(
# Taking sequence of elements
c(2, 4, 5, 7, 1, 8, 9, 2),
print(A)
Output:
, , 1
[,1] [,2]
[1,] 2 5
[2,] 4 7
, , 2
[,1] [,2]
[1,] 1 9
[2,] 8 2
Accessing arrays:
Example:
Output:
c(vector, values)
append(vector, values):
Using the length function of the array
Example:
Output:
Example:
Output:
R – Array
Multidimensional Array
Array Operations
Factors:
Factors are the data objects which are used to categorize the data and
store it as levels. They are useful for storing categorical data.
Example:
# Creating a vector
x<-c("female", "male", "other", "female", "other")
Output:
Example:
Output:
[1] "other"
Modifying of a Factor:
After a factor is formed, its components can be modified but the new
values which need to be assigned must be in the predefined level.
Example:
Output:
R – Factors
Level Ordering of Factors
Error Handling
Error Handling is a process in which we deal with unwanted or
anomalous errors which may cause abnormal termination of the
program during its execution. In R
Error handling can be done using tryCatch(). The first argument of this
function is the expression which is followed by the condition specifying
how to handle the conditions.
Syntax:
check = tryCatch({
expression
}, warning = function(w){
code that handles the warnings
}, error = function(e){
code that handles the errors
}, finally = function(f){
clean-up code
})
Example:
# Evaluation of tryCatch
check <- function(expression){
tryCatch(expression,
warning = function(w){
message("warning:\n", w)
},
error = function(e){
message("error:\n", e)
},
finally = {
message("Completed")
})
}
check({10/2})
check({10/0})
check({10/'noe'})
Output:
Refer to the below articles to get detailed information about
error handling in R
Bar Chart:
R uses the function barplot() to create bar charts. Here, both vertical
and Horizontal bars can be drawn.
Example:
R
# Create the data for the chart
A <- c(17, 32, 8, 53, 1)
Output:
Histograms:
Example:
Scatter plots:
Example:
Output:
Note: For more information, refer Scatter plots in R Language
Line Chart:
Example:
Output:
Note: For more information, refer Line Graphs in R Language.
Pie Charts:
R uses the function pie() to create pie charts. It takes positive numbers
as a vector input.
Example:
Output:
Note: For more information, refer Pie Charts in R Language
Boxplots:
Output:
Note: For more information, refer Boxplots in R Language
Statistics
Statistics simply means numerical data, and is field of math that
generally deals with collection of data, tabulation, and interpretation
of numerical data. It is an area of applied mathematics concern with
data collection analysis, interpretation, and presentation. Statistics
deals with how data can be used to solve complex problems.
Example:
print(mean(A))
print(median(A))
Output:
[1] 21.6
[1] 14.5
[1] 17
Normal Distribution:
Normal Distribution tells about how the data values are distributed.
For example, the height of the population, shoe size, IQ level, rolling a
dice, and many more. In R, there are 4 built-in functions to generate
normal distribution:
Example:
Output:
Note: For more information refer Normal Distribution in R
dbinom()
dbinom(k, n, p)
pbinom()
pbinom(k, n, p)
qbinom()
qbinom(P, n, p)
rbinom()
rbinom(n, N, p)
Example:
Output:
Note: For more information, refer Binomial Distribution in R
Programming
Output:
Similar Reads
Getting the Modulus of Set or View the Graphics
the Determinant of a Palette in R
Matrix in R… Programming - palett…
Article Contributed By :
GeeksforGeeks
Company Explore
About Us Job-A-Thon Hiring Challenge
Legal Hack-A-Thon
Careers GfG Weekly Contest
In Media Offline Classes (Delhi/NCR)
Contact Us DSA in JAVA/C++
Advertise with us Master System Design
Campus Training Program Master CP
Commerce UPSC
Accountancy Polity Notes
Business Studies Geography Notes
Economics History Notes
Human Resource Management (HRM) Science and Technology Notes
Management Economics Notes
Income Tax Important Topics in Ethics
Finance UPSC Previous Year Papers
Statistics for Economics