[go: up one dir, main page]

0% found this document useful (0 votes)
2 views57 pages

Unit 5

The document provides an overview of R programming, including its definition, differences from Python, and installation instructions for Windows and Linux. It covers basic syntax, data types, functions, conditional statements, and loops in R, along with examples for better understanding. Additionally, it discusses string manipulation and the use of comments and keywords in R programming.

Uploaded by

Lakshmi Marineni
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)
2 views57 pages

Unit 5

The document provides an overview of R programming, including its definition, differences from Python, and installation instructions for Windows and Linux. It covers basic syntax, data types, functions, conditional statements, and loops in R, along with examples for better understanding. Additionally, it discusses string manipulation and the use of comments and keywords in R programming.

Uploaded by

Lakshmi Marineni
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/ 57

UNIT V

R Programming
What is R
• R is a popular programming language used for statistical computing
and graphical presentation.
• Its most common use is to analyze and visualize data
Difference between R & Python
S.No
Parameters R Python
Objective Its main objective is to perform data analysis Python is used for deployment and
1.

and statistics. production.


Primary Users Scholar and R&D are the primary users of R. Programmers and developers are the
2.

primary users of R.
Flexibility In R, we can easily use the available libraries. In Python, we can easily construct new
3.

models from scratch.


Learning Curve In R, the learning curve is difficult at the The learning curve is linear and smooth.
4.

beginning.
Popularity of Less popular compare to python More popular compare to R
5.

programming
language
Integration R runs locally. It is well-integrated with the app.
7.

Task In R, we can easily get the primary results.


Python is good to deploy the algorithm.
8.

Database size R handles the huge size of data. It will also handle the huge size of data.
9.

IDE Rstudio Spyder, Ipthon Notebook.


10.

Packages and library tydiverse, ggplot2, caret, and zoo. Pandas, scipy, scikit-learn, TensorFlow,
11.

caret.
Advantages 1. Beautiful graph construction. 1. Notebooks help to share data with
12.

colleagues, and python has a jupyter


2. A large catalog is available for data notebook.
analysis.
Environment Setup
Windows Installation
• You can download the Windows installer version of R from
R-3.2.2 for Windows (32/64 bit) and save it in a local directory.
• As it is a Windows installer (.exe) with a name "R-version-win.exe".
• You can just double click and run the installer accepting the default settings.
• If your Windows is 32-bit version, it installs the 32-bit version.
• But if your windows is 64-bit, then it installs both the 32-bit and 64-bit versions.
• After installation you can locate the icon to run the Program in a directory
structure "R\R3.2.2\bin\i386\Rgui.exe" under the Windows Program Files.
• Clicking this icon brings up the R-GUI which is the R console to do R
Programming.
Linux Installation
• R is available as a binary for many versions of Linux at the location
R Binaries.
• The instruction to install Linux varies from flavor to flavor.
• However, if you are in a hurry, then you can use yum command to
install R as follows −
• Above command will install core functionality of R programming along
with standard packages, still you need additional package, then you can
launch R prompt as follows −
• $R
• Now you can use install command at R prompt to install the required
package. For example, the following command will
install plotrix package which is required for 3D charts.
• install.packages("plotrix")
Syntax of R program
A program in R is made up of three things: Variables, Comments, and
Keywords.
Variables are used to store the data,
Comments are used to improve code readability, and Keywords are
reserved words that hold a specific meaning to the compiler.
Reading from the keyboard:To read the data from the keyboard, we use
three different functions; scan(), readline(), print().
scan() : This is used for reading data into the input vector or an input list
from the environment console or file.
readline() : #always read characher data type.
print(): A print function simply displays the contents of its argument
object. New printing methods can be easily added for new classes
through this generic function.
Input functions
readline() & Using scan() method

• 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
• Syntax:
var = readline();
var = as.integer(var);
• scan()read multiple values
• Syntax:
x = scan()
scan() method is taking input continuously, to terminate the input
process, need to press Enter key 2 times on the console.
Output functions print() & Cat()
Print() prints only one parameter. Does not concatenate multiple
outputs.
A=10.
Print(a) =10
print(”a”) =“a”
print(“a=“,a) =“a=“ not print value
Cat() concatenate multiple values.
Variables in R
• variables which like any other programming language are the name
given to reserved memory locations that can store any type of data. In
R, the assignment can be denoted in three ways:
• = (Simple Assignment)
• <- (Leftward Assignment)
• -> (Rightward Assignment)
Comments in R
• Comments are a way to improve your code’s readability and are only
meant for the user so the interpreter ignores it.
• Only single-line comments are available in R but we can also use
multiline comments by using a simple trick which is shown below.
• Single line comments can be written by using # at the beginning of the
statement.
• Example:
• #hellow How are You?
Keywords in R
Keywords are the words reserved by a program because they have a
special meaning thus a keyword can’t be used as a variable name,
function name, etc. We can view these keywords by using either
help(reserved).

 if, else, repeat, while, function, for, in, next and break are used for control-flow statements and
declaring user-defined functions.
 The ones left are used as constants like TRUE/FALSE are used as boolean constants.
 NaN defines Not a Number value and NULL are used to define an Undefined value.
 Inf is used for Infinity values.
Basic Data Types
• Each variable in R has an associated data type.
• Each R-Data Type requires different amounts of memory and has
some specific operations which can be performed over it.
• Basic data types in R can be divided into the following types:
•numeric - (10.5, 55, 787)
•integer - (1L, 55L, 100L, where the letter "L" declares
this as an integer)
•complex - (9 + 3i, where "i" is the imaginary part)
•character (a.k.a. string) - ("k", "R is exciting", "FALSE",
"11.5")
•logical (a.k.a. boolean) - (TRUE or FALSE)
We can use the class() function to check the data type of a variable:
Creating a Function & Call a Function
To create a function, use
the function() keyword:
my_function <- function() { # create a
function with the name my_function
print("Hello World!")
}

To call a function, use the function name followed


by parenthesis, like my_function():

my_function <- function() {


print("Hello World!")
}

my_function() # call the function named


my_function
Arguments

Information can be passed into functions as arguments.


Arguments are specified after the function name, inside the parentheses.
You can add as many arguments as you want, just separate them with a comma.
The following example has a function with one argument (fname).
When the function is called, we pass along a first name, which is used inside the
function to print the full name:
rfun <- function(x) {
return (5 * x)
}
print(rfun(3))
print(rfun(5))
rfun(9)
OUTPUT:
[1] 15[1] 25[1] 45
Nested Functions
• There are two ways to create a nested function:
• Call a function within another function.
• Write a function within a function. Example
Write a function within a
Example function:
Call a function within another function: Outfun <- function(x) {
Nfun <- function(x, y) Infun <- function(y) {
a <- x + y
{ a <- x + y
return(a)
return(a) }
} return (Infun)
Nfun(Nfun(2, 2), Nfun(3, 3)) }
output <- Outfun(3) # To call the
Output: [1] 10 Outer_func
output(5)
Output: [1] 8
R - Strings
• Any value written within a pair of single quote or double quotes in R is treated as
a string. Internally R stores every string within double quotes, even when you
create them with single quote.
• Rules Applied in String Construction
• The quotes at the beginning and end of a string should be both double quotes or
both single quote. They can not be mixed.
• Double quotes can be inserted into a string starting and ending with single quote.
• Single quote can be inserted into a string starting and ending with double quotes.
• Double quotes can not be inserted into a string starting and ending with double
quotes.
• Single quote can not be inserted into a string starting and ending with single
quote.
Examples of Valid Strings
Following examples clarify the rules about creating a string in R.

a <- 'Start and end with single quote‘


print(a)
b <- "Start and end with double quotes“
print(b)
c <- "single quote ' in between double quotes“
print(c)
d <- 'Double quotes " in between single quote‘
print(d)
Output:
[1] "Start and end with single quote“
[1] "Start and end with double quotes“
[1] "single quote ' in between double quote“
[1] "Double quote \" in between single quote"
String Manipulation
Concatenating Strings - paste() function
Many strings in R are combined using the paste() function. It can take any number of arguments to be combined together.
Syntax
The basic syntax for paste function is −
paste(..., sep = " ", collapse = NULL)

Output:
a <- "Hello“ [1] "Hello How are you? “
[1] "Hello-How-are you? “

b <- 'How‘ [1] "HelloHoware you? "

c <- "are you? “


print(paste(a,b,c))
print(paste(a,b,c, sep = "-"))
print(paste(a,b,c, sep = "", collapse = ""))
String Manipulation in R
Programming
• nchar () :
• toupper ()
• tolower ()
• substr ()
• grep ()
• paste ()
• strsplit ()
• sprintf ()
• cat ()
• sub ()
Changing the case - toupper() &
tolower() functions
These functions change the case of characters of a string.
Syntax
The basic syntax for toupper() & tolower() function is −
toupper(x)
tolower(x)
Following is the description of the parameters used −
•x is the vector input.
# Changing to Upper case.
result <- toupper("Changing To Upper")
print(result)# Changing to lower case.
result <- tolower("Changing To Lower")
print(result)
Conditional Statements
if-else Statements
Syntax
if (condition) { # Code to execute if condition is TRUE }
Else { # Code to execute if condition is FALSE }
if-else if-else Statements
Syntax
if (condition1) { # Code to execute if condition1 is TRUE }
else if (condition2) { # Code to execute if condition2 is TRUE }
else { # Code to execute if no condition is TRUE }
switch Statement
switch(expr, case1, case2, ..., caseN)
Example program using the switch statement
# Example program using the switch statement
day <- "Monday"
message <- switch(day,
"Monday" = "It's the start of the workweek.",
"Tuesday" = "Another workday.",
"Wednesday" = "Midweek!",
"Thursday" = "Almost there!",
"Friday" = "TGIF!",
"Saturday" = "Weekend!",
"Sunday" = "Weekend!"
)
print(message)
Output: [1] "It's the start of the workweek."
Loops in R (for, while, repeat)
• There are three types of loops in R programming:
• For Loop
• While Loop
• Repeat Loop
• For Loop in R
• It is a type of control statement that enables one to easily construct an R loop
that has to run statements or a set of statements multiple times. For R loop is
commonly used to iterate over items of a sequence. It is an entry-controlled
loop, in this loop, the test condition is tested first, then the body of the loop is
executed, the loop body would not be executed if the test condition is false. R
– For loop Syntax:

for (value in sequence)


{ statement
}
Example of for Loop
# R program to demonstrate the use of for loop
# using for loop
for (val in 1: 5)
{
print(val)
}
Output:
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
Example of for Loop
# Create a list of numbers
my_list <- list(1, 2, 3, 4, 5)
# Loop through the list and print each element
for (i in my_list)
{
current_element <- my_list[i]
print(paste("The current element is:", current_element))
}
Output:
[1] "The current element is: 1"
[1] "The current element is: 2"
[1] "The current element is: 3"
[1] "The current element is: 4"
[1] "The current element is: 5"
R For-Loop on a Matrix
# Create a 3x3 matrix of integers
my_matrix <- matrix(1:9, nrow = 3)
# Loop through the matrix and print each element
for (i in seq_len(nrow(my_matrix))) {
for (j in seq_len(ncol(my_matrix))) {
current_element <- my_matrix[i, j]
print(paste("The current element is:", current_element))
}
}
Output:
[1] "The current element is: 1"
[1] "The current element is: 4"
[1] "The current element is: 7"
[1] "The current element is: 2"
[1] "The current element is: 5"
[1] "The current element is: 8"
[1] "The current element is: 3"
[1] "The current element is: 6"
[1] "The current element is: 9"
While Loop in R
It is a type of control statement that will run a statement or a set of
statements repeatedly unless the given condition becomes false. It is
also an entry-controlled loop, in this loop, the test condition is tested
first, then the body of the loop is executed, the loop body would not be
executed if the test condition is false.
R – While loop Syntax:

while ( condition )
{
statement
}
Program to display numbers from 1 to 5 using a while
loop in R.
# R program to demonstrate the use of while loop
val = 1
# using while loop
while (val <= 5)
{
print(val)
val = val + 1
}
Output:
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
Repeat Loop in R
It is a simple loop that will run the same statement or a group of statements
repeatedly until the stop condition has been encountered. Repeat loop does not
have any condition to terminate the loop, a programmer must specifically place a
condition within the loop’s body and use the declaration of a break statement to
terminate this loop. If no condition is present in the body of the repeat loop then
it will iterate infinitely.
R – Repeat loop Syntax:
Repeat
{
statement
if( condition )
{
break
}
}
Example 1: Program to display numbers from 1
to 5 using a repeat loop in R.
val = 1
repeat
{
print(val)
val = val + 1
if(val > 5)
{
break
}
}
Output:
[1] 1
[1] 2
[1] 3
[1] 4
Jump Statements in Loop
Break Statement: The break keyword is a jump statement that is used to terminate the loop at a particular
iteration.
Next Statement: The next keyword is a jump statement which is used to skip a particular iteration in the loop.
Example of next statement:
for (val in 1: 5)
{
if (val == 3)
{
next
}
print(val)
}
Output:
[1] 1
[1] 2
[1] 4
[1] 5
R Vectors
R Vectors are the same as the arrays in R language which are used to
hold multiple data values of the same type.
One major key point is that in R Programming Language the indexing
of the vector will start from ‘1’ and not from ‘0’.
We can create numeric vectors and character vectors as well.
Types of R vectors

• Numeric vectors: Numeric vectors are those which contain numeric values such as integer,
float, etc.
• Example:
• v1<- c(4, 5, 6, 7)
• typeof(v1) #"double“
• v2<- c(1L, 4L, 2L, 5L)
• typeof(v2) #"integer"
• Character vectors: Character vectors in R contain alphanumeric values and special
characters.
• Example:
• v1<- c('geeks', '2', 'hello', 57)
• typeof(v1) #"character"
• Logical vectors: Logical vectors in R contain Boolean values such as TRUE, FALSE and NA for
Null values.
• Example:
• v1<- c(TRUE, FALSE, TRUE, NA)
List creation & Accessing
List: A list in R can contain many different data types inside it.
A list is a collection of data which is ordered and changeable.
To create a list, use the list() function:
# List of strings
thislist <- list("apple", "banana", "cherry") #create a list
thislist# Print the list
thislist[1] # Access Lists
thislist[1] <- "blackcurrant” #Change Item Value
length(thislist) #List Length
" cherry " %in% thislist #Check if Item Exists use the %in% operator
append(thislist, "orange") # Add List Items
newlist <- thislist[-1] # Remove List Items
Join Two Lists
list1 <- list("a", "b", "c")
list2 <- list(1,2,3)
list3 <- c(list1,list2) #The most common way is to use the c() function, which combines two elements together
list3
Matrices
A matrix is a two dimensional data set with columns and rows.
A column is a vertical representation of data, while a row is a horizontal representation of data.
A matrix can be created with the matrix() function. Specify the nrow and ncol parameters to get the amount of rows
and columns:
Example:
thismatrix <- matrix(c("apple", "banana", "cherry", "orange"), nrow = 2, ncol = 2)
print(thismatrix)
thismatrix[1, 2]#Access Matrix Items
thismatrix[2,]#Access Matrix Items
thismatrix[,2]#Access Matrix Items
thismatrix[c(1,2),]#Access More Than One Row
thismatrix[, c(1,2)]#Access More Than One Column
newmatrix <- rbind(thismatrix, c("strawberry", "blueberry", "raspberry"))
#rbind() function to add additional rows in a Matrix
thismatrix <- thismatrix[-c(1), -c(1)] #Remove the first row and the first column
"apple" %in% thismatrix #Check if an Item Exists
dim(thismatrix)#Number of Rows and Columns
length(thismatrix) #Matrix Length
R Factors
• Factors are used to categorize data.
• Examples of factors are:
• Demography: Male/Female
• Music: Rock, Pop, Classic, Jazz
• Training: Strength, Stamina
• To create a factor, use the factor() function and add a vector as argument:
• Example:
# Create a factor
music_genre <- factor(c("Jazz", "Rock", "Classic", "Classic", "Pop", "Jazz", "Rock",
"Jazz"))
print(music_genre) # Print the factor
Output:
[1] Jazz Rock Classic Classic Pop Jazz Rock Jazz
Levels: Classic Jazz Pop Rock
Example 2:
music_genre <-factor(c("Jazz", "Rock", "Classic", "Classic", "Pop", "Jazz", "Rock", "Jazz"))
music_genre #print
levels(music_genre)#only print the levels, use the levels() function
length(music_genre) #Factor Length
music_genre[4] #Access Factors
music_genre[3] <- "Pop“ #Change Item Value
music_genre[3]
Output:
[1] Jazz Rock Classic Classic Pop Jazz Rock Jazz
Levels: Classic Jazz Pop Rock
[1] "Classic" "Jazz" "Pop" "Rock"
[1] 8
[1] Classic
Levels: Classic Jazz Pop Rock
[1] Pop
Levels: Classic Jazz Pop Rock
Arrays
• Arrays are essential data storage structures defined by a fixed number of dimensions. Arrays
are used for the allocation of space at contiguous memory locations.
• In R Programming Language Uni-dimensional arrays are called vectors with the length being
their only dimension.
• Two-dimensional arrays are called matrices, consisting of fixed numbers of rows and columns.
• R Arrays consist of all elements of the same data type.
• Vectors are supplied as input to the function and then create an array based on the number of
dimensions.
• An R array can be created with the use of array() the function. A list of
elements is passed to the array() functions along with the dimensions as
required.
• Syntax:
array(data, dim = (nrow, ncol, nmat), dimnames=names)
where
• nmat: Number of matrices of dimensions nrow * ncol
• dimnames : Default value = NULL.
Data Frames & Structure
• Data Frames in R Language are generic data objects of R that are
used to store tabular data.
• Data frames can also be interpreted as matrices where each column
of a matrix can be of different data types.
• R DataFrame is made up of three principal components, the data,
rows, and columns.
• The data is presented in tabular form, which makes it easier to
operate and understand
Create Dataframe in R
Programming Language
• To create an R data frame use data.frame() function and then pass each of the vectors
you have created as arguments to the function.
# R program to create dataframe
# creating a data frame
friend.data <- data.frame(
friend_id = c(1:5),
friend_name = c("Sachin", "Sourav",
"Dravid", "Sehwag",
"Dhoni"),
stringsAsFactors = FALSE
)
# print the data frame
print(friend.data)
Output:
'data.frame': 5 obs. of 2 variables:
$ friend_id : int 1 2 3 4 5
$ friend_name: chr "Sachin" "Sourav" "Dravid" "Sehwag" ...
R – Charts and Graphs
R – Charts and Graphs
R language is mostly used for statistics and data analytics purposes to
represent the data graphically in the software. To represent those data
graphically, charts and graphs are used in R.
• R – graphs: There are hundreds of charts and graphs present in R. For
example, bar plot, box plot, mosaic plot, dot chart, coplot, histogram,
pie chart, scatter graph, etc.
• Types of R – Charts
1. Bar Plot or Bar Chart
2. Pie Diagram or Pie Chart
3. Histogram
4. Scatter Plot
5. Box Plot
6. Line Graphs
Bar Plot or Bar Chart
Bar plot or Bar Chart in R is used to represent the values in data vector
as height of the bars. The data vector passed to the function is
represented over y-axis of the graph.
Bar chart can behave like histogram by using table() function instead of
data vector.
• Syntax: barplot(data, xlab, ylab)
• where:
• data is the data vector to be represented on y-axis
• xlab is the label given to x-axis
• ylab is the label given to y-axis
Note: To know about more optional parameters in barplot() function,
We use help(barplot) command in R console
# defining vector
x <- c(7, 15, 23, 12, 44, 56, 32)

# output to be present as PNG file


png(file = "barplot.png")

# plotting vector
barplot(x, xlab = " Audience",
ylab = "Count", col = "white",
col.axis = "darkgreen",
col.lab = "darkgreen")

# saving the file


dev.off()
Pie Diagram or Pie Chart
• Pie chart is a circular chart divided into different segments according to the ratio of data
provided. The total value of the pie is 100 and the segments tell the fraction of the whole pie.
• It is another method to represent statistical data in graphical form and pie() function is used
to perform the same.
• Syntax: pie(x, labels, col, main, radius)
• where,
• x is data vector
• labels shows names given to slices
• col fills the color in the slices as given parameter
• main shows title name of the pie chart
• radius indicates radius of the pie chart. It can be between -1 to +1
• Note: To know about more optional parameters in pie() function, use help(“pie”) command
in the R console:
• Pie chart in 3D can also be created in R by using following syntax but requires plotrix library.
• Syntax: pie3D(x, labels, radius, main)
• Note: To know about more optional parameters in pie3D() function, use help(“pie3D”)
command in R console:
Assume, vector x indicates the number of
articles present on categories names(x)
# defining vector x with number of articles
x <- c(210, 450, 250, 100, 50, 90)
# defining labels for each value in x
names(x) <- c("Algo", "DS", "Java", "C", "C++", "Python")
# output to be present as PNG file
png(file = "piechart.png")
# creating pie chart
pie(x, labels = names(x), col = "white",
main = "Articles on ICFAI", radius = -1,
col.main = "darkgreen")
# saving the file
dev.off()
Histogram
Histogram is a graphical representation used to create a graph with bars
representing the frequency of grouped data in vector.
Histogram is same as bar chart but only difference between them is
histogram represents frequency of grouped data rather than data itself.
• Syntax: hist(x, col, border, main, xlab, ylab)
• where:
• x is data vector
• col specifies the color of the bars to be filled
• border specifies the color of border of bars
• main specifies the title name of histogram
• xlab specifies the x-axis label
• ylab specifies the y-axis label
• Note: To know about more optional parameters in hist() function, use
help(“hist”)command in R console:
# defining vector
x <- c(21, 23, 56, 90, 20, 7, 94, 12,
57, 76, 69, 45, 34, 32, 49, 55, 57)

# output to be present as PNG file


png(file = "hist.png")

# hist(x, main = "Histogram of Vector x",


xlab = "Values",
col.lab = "darkgreen",
col.main = "darkgreen")

# saving the file


dev.off()
Scatter Plot
A Scatter plot is another type of graphical representation used to plot the points to show
relationship between two data vectors.
One of the data vectors is represented on x-axis and another on y-axis.
• Syntax: plot(x, y, type, xlab, ylab, main)
• Where,
• x is the data vector represented on x-axis
• y is the data vector represented on y-axis
• type specifies the type of plot to be drawn. For example, “l” for lines, “p” for points, “s” for stair steps,
etc.
• xlab specifies the label for x-axis
• ylab specifies the label for y-axis
• main specifies the title name of the graph
Note: To know about more optional parameters in plot() function, use the help(“plot”)command in R
console:

If a scatter plot has to be drawn to show the relation between 2 or more vectors or to plot the scatter plot
matrix between the vectors, then pairs() function is used to satisfy the criteria.
• yntax: pairs(~formula, data)
• where,
• ~formula is the mathematical formula such as ~a+b+c
• data is the dataset form where data is taken in formula.
# taking input from dataset Orange already
# present in R
orange <- Orange[, c('age', 'circumference')]

# output to be present as PNG file


png(file = "plot.png")

# plotting
plot(x = orange$age, y = orange$circumference, xlab = "Age",
ylab = "Circumference", main = "Age VS Circumference",
col.lab = "darkgreen", col.main = "darkgreen",
col.axis = "darkgreen")

# saving the file


dev.off()
Box Plot
Box plot shows how the data is distributed in the data vector.
It represents five values in the graph i.e., minimum, first quartile,
second quartile(median), third quartile, the maximum value of the data
vector.
• Syntax: boxplot(x, xlab, ylab, notch)
• where,
• x specifies the data vector
• xlab specifies the label for x-axis
• ylab specifies the label for y-axis
• notch, if TRUE then creates notch on both the sides of the box
• Note: To know about more optional parameters in boxplot() function,
use the help(“boxplot”) command in R console:
# defining vector with ages of employees
x <- c(42, 21, 22, 24, 25, 30, 29, 22,
23, 23, 24, 28, 32, 45, 39, 40)

# output to be present as PNG file


png(file = "boxplot.png")

# plotting
boxplot(x, xlab = "Box Plot", ylab = "Age",
col.axis = "darkgreen", col.lab = "darkgreen")

# saving the file


dev.off()
Line Graphs
A line graph is a chart that is used to display information in the form of a series of data points.
It utilizes points and lines to represent change over time.
Line graphs are drawn by plotting different points on their X coordinates and Y coordinates, then by
joining them together through a line from beginning to end.
The graph represents different values as it can move up and down based on the suitable variable.
The plot() function in R is used to create the line graph.
• Syntax: plot(v, type, col, xlab, ylab)
• Parameters:
• v: This parameter is a contains only the numeric values
• type: This parameter has the following value:
• “p” : This value is used to draw only the points.
• “l” : This value is used to draw only the lines.
• “o”: This value is used to draw both points and lines
• xlab: This parameter is the label for x axis in the chart.
• ylab: This parameter is the label for y axis in the chart.
• main: This parameter main is the title of the chart.
• col: This parameter is used to give colors to both the points and lines.
# Create the data for the chart.
v <- c(17, 25, 38, 13, 41)

# Plot the bar chart.


plot(v, type = "o", col = "green",
xlab = "Month", ylab = "Article Written",
main = "Article Written chart")

You might also like