[go: up one dir, main page]

0% found this document useful (0 votes)
23 views35 pages

R Lab Record 2024

The document provides an overview of creating and manipulating matrices and vectors in R programming. It explains how to create matrices using the matrix() function, access and modify elements, and perform operations like transposing and binding. Additionally, it covers the definition and creation of vectors, including their properties and basic operations.

Uploaded by

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

R Lab Record 2024

The document provides an overview of creating and manipulating matrices and vectors in R programming. It explains how to create matrices using the matrix() function, access and modify elements, and perform operations like transposing and binding. Additionally, it covers the definition and creation of vectors, including their properties and basic operations.

Uploaded by

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

Ex No

Date

1. Creation and manipulation of matrix in R.


Matrix is a two dimensional data structure in R programming.
Matrix is similar to vector but additionally contains the dimension attribute. All attributes of an
object can be checked with the attributes() function (dimension can be checked directly with
the dim() function).
We can check if a variable is a matrix or not with the class() function.

How to create a matrix in R programming?


Matrix can be created using the matrix() function.
Dimension of the matrix can be defined by passing appropriate value for
arguments nrow and ncol.
Providing value for both dimension is not necessary. If one of the dimension is provided, the
other is inferred from length of the data.
> matrix(1:9, nrow = 3, ncol = 3)
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
> # same result is obtained by providing only one dimension
> matrix(1:9, nrow = 3)
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
We can see that the matrix is filled column-wise. This can be reversed to row-wise filling by
passing TRUE to the argument byrow.
> matrix(1:9, nrow=3, byrow=TRUE) # fill matrix row-wise
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
[3,] 7 8 9
In all cases, however, a matrix is stored in column-major order internally as we will see in the
subsequent sections.
It is possible to name the rows and columns of matrix during creation by passing a 2 element list
to the argument dimnames.
> x <- matrix(1:9, nrow = 3, dimnames = list(c("X","Y","Z"), c("A","B","C")))
>x
ABC
X147
Y258
Z369
These names can be accessed or changed with two helpful functions colnames() and rownames().
> colnames(x)
[1] "A" "B" "C"
> rownames(x)
[1] "X" "Y" "Z"
> # It is also possible to change names
> colnames(x) <- c("C1","C2","C3")
> rownames(x) <- c("R1","R2","R3")
>x
C1 C2 C3
R1 1 4 7
R2 2 5 8
R3 3 6 9
Another way of creating a matrix is by using functions cbind() and rbind() as in column bind and
row bind.
> cbind(c(1,2,3),c(4,5,6))
[,1] [,2]
[1,] 1 4
[2,] 2 5
[3,] 3 6
> rbind(c(1,2,3),c(4,5,6))
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
Finally, you can also create a matrix from a vector by setting its dimension using dim().
> x <- c(1,2,3,4,5,6)
>x
[1] 1 2 3 4 5 6
> class(x)
[1] "numeric"
> dim(x) <- c(2,3)
>x
[,1] [,2] [,3]
[1,] 1 3 5
[2,] 2 4 6
> class(x)
[1] "matrix"
How to access Elements of a matrix?
We can access elements of a matrix using the square bracket [ indexing method. Elements can be
accessed as var[row, column]. Here rows and columns are vectors.
Using integer vector as index
We specify the row numbers and column numbers as vectors and use it for indexing.
If any field inside the bracket is left blank, it selects all.
We can use negative integers to specify rows or columns to be excluded.
>x
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
> x[c(1,2),c(2,3)] # select rows 1 & 2 and columns 2 & 3
[,1] [,2]
[1,] 4 7
[2,] 5 8
> x[c(3,2),] # leaving column field blank will select entire columns
[,1] [,2] [,3]
[1,] 3 6 9
[2,] 2 5 8
> x[,] # leaving row as well as column field blank will select entire matrix
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
> x[-1,] # select all rows except first
[,1] [,2] [,3]
[1,] 2 5 8
[2,] 3 6 9
One thing to notice here is that, if the matrix returned after indexing is a row matrix or column
matrix, the result is given as a vector.
> x[1,]
[1] 1 4 7
> class(x[1,])
[1] "integer"
This behavior can be avoided by using the argument drop = FALSE while indexing.
> x[1,,drop=FALSE] # now the result is a 1X3 matrix rather than a vector
[,1] [,2] [,3]
[1,] 1 4 7
> class(x[1,,drop=FALSE])
[1] "matrix"
It is possible to index a matrix with a single vector.
While indexing in such a way, it acts like a vector formed by stacking columns of the matrix one
after another. The result is returned as a vector.
>x
[,1] [,2] [,3]
[1,] 4 8 3
[2,] 6 0 7
[3,] 1 2 9
> x[1:4]
[1] 4 6 1 8
> x[c(3,5,7)]
[1] 1 0 3
Using logical vector as index

Two logical vectors can be used to index a matrix. In such situation, rows and columns where the
value is TRUE is returned. These indexing vectors are recycled if necessary and can be mixed
with integer vectors.
>x
[,1] [,2] [,3]
[1,] 4 8 3
[2,] 6 0 7
[3,] 1 2 9
> x[c(TRUE,FALSE,TRUE),c(TRUE,TRUE,FALSE)]
[,1] [,2]
[1,] 4 8
[2,] 1 2
> x[c(TRUE,FALSE),c(2,3)] # the 2 element logical vector is recycled to 3 element vector
[,1] [,2]
[1,] 8 3
[2,] 2 9
It is also possible to index using a single logical vector where recycling takes place if necessary.
> x[c(TRUE, FALSE)]
[1] 4 1 0 3 9
In the above example, the matrix x is treated as vector formed by stacking columns of the matrix
one after another, i.e., (4,6,1,8,0,2,3,7,9).
The indexing logical vector is also recycled and thus alternating elements are selected. This
property is utilized for filtering of matrix elements as shown below.
> x[x>5] # select elements greater than 5
[1] 6 8 7 9
> x[x%%2 == 0] # select even elements
[1] 4 6 8 0 2
Using character vector as index

Indexing with character vector is possible for matrix with named row or column. This can be
mixed with integer or logical indexing.
>x
ABC
[1,] 4 8 3
[2,] 6 0 7
[3,] 1 2 9
> x[,"A"]
[1] 4 6 1
> x[TRUE,c("A","C")]
AC
[1,] 4 3
[2,] 6 7
[3,] 1 9
> x[2:3,c("A","C")]
AC
[1,] 6 7
[2,] 1 9

How to modify a matrix in R?


We can combine assignment operator with the above learned methods for accessing elements of
a matrix to modify it.
>x
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
> x[2,2] <- 10; x # modify a single element
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 10 8
[3,] 3 6 9
> x[x<5] <- 0; x # modify elements less than 5
[,1] [,2] [,3]
[1,] 0 0 7
[2,] 0 10 8
[3,] 0 6 9
A common operation with matrix is to transpose it. This can be done with the function t().
> t(x) # transpose a matrix
[,1] [,2] [,3]
[1,] 0 0 0
[2,] 0 10 6
[3,] 7 8 9
We can add row or column using rbind() and cbind() function respectively. Similarly, it can be
removed through reassignment.
> cbind(x, c(1, 2, 3)) # add column
[,1] [,2] [,3] [,4]
[1,] 0 0 7 1
[2,] 0 10 8 2
[3,] 0 6 9 3
> rbind(x,c(1,2,3)) # add row
[,1] [,2] [,3]
[1,] 0 0 7
[2,] 0 10 8
[3,] 0 6 9
[4,] 1 2 3
> x <- x[1:2,]; x # remove last row
[,1] [,2] [,3]
[1,] 0 0 7
[2,] 0 10 8
Dimension of matrix can be modified as well, using the dim() function.
>x
[,1] [,2] [,3]
[1,] 1 3 5
[2,] 2 4 6
> dim(x) <- c(3,2); x # change to 3X2 matrix
[,1] [,2]
[1,] 1 4
[2,] 2 5
[3,] 3 6
> dim(x) <- c(1,6); x # change to 1X6 matrix
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 1 2 3 4 5 6
Ex No
Date

2. Creation and manipulation of Vectors, Factors in R.


Definition of a variable
Variables are objects in R that you can use to store values. It can consist of a single value, basic
or complex arithmetic operations, or even be more complex such as a column in a data matrix
or a data frame. We will see these complex forms in the following steps of this course.
Definition of a vector
A vector is substantially a list of variables, and the simplest data structure in R. A vector
consists of a collection of numbers, arithmetic expressions, logical values or character strings
for example. However, each vector must have all components of the same mode, that are called
numeric, logical, character, complex, raw.
Let’s create a simple variable called x. We need to assign elements to this variable.
The assignment to a variable can be done in 2 different but equivalent ways, using either the ““
or “=” operators. You can retrieve the value of x simply by typing x

>x 3*4+2*5+3
>x=3*4+2*5+3
>x
[1] 25
Let’s create another variable called y that can either contain a new value or for example contain a
basic or more complex operation on the first variable x

> y x^4 - 4*x + 5


>x
[1] 390530
Note 1. Naming a Variable is not trivial and must be done appropriately:
Variable names can contain letters, numbers, underscores and periods
Variable names cannot start with a number or an underscore
Variable names cannot contain spaces at all

> x.length 3*2


> x.length
[1] 6
> _x.length 3*2
Error : unexpected input in "_"
> 3x.length 3*2
Error : unexpected symbol in "3x.length"

Note 2. Long Variable names are allowed but must be formatted using:

 Periods to separate words: x.y.z


 Underscores to separate words: x_y_z
 Camel Case to separate words: XxYyZz

> x.length 3*2


> x.length
[1] 6
> x_length 3*2
> x_length
[1] 6
> xLength 3*2
> xLength
[1] 6
How to create and manipulate Vectors

Step 1. A vector can be created using an in-built function in R called c(). Elements must be
comma-separated.

> c(10, 20, 30)


[1] 10 20 30

Step 2. A vector can be of different modes: numeric (and arithmetic), logical, or can consist of
characters

> c(1.1, 2.2, 3.5) # numeric


[1] 1.1 2.2 3.5
>
> c(FALSE, TRUE, FALSE) # logical
[1] FALSE TRUE FALSE
>
> c("Darth Vader", "Luke Skywalker", "Han Solo") # character
[1] "Darth Vader" "Luke Skywalker" "Han Solo"

Note. Please note that when the value is a character data type, quotations must be used around
each value, such as in “Han Solo”
Step 3. A vector can be assigned to a variable name, using 3 methods: either using the ““ or “=”
operators or the assign function. You will very rarely see the last method which is to revert
the order of assignment

> assign("x", c(10, 20, 30))


>x
[1] 10 20 30
>
> x c(10, 20, 30)
>x
[1] 10 20 30
>
> x = c(10, 20, 30)
>x
[1] 10 20 30
>
> c(10, 20, 30) -> x
>x
[1] 10 20 30

Step 4. In R, an object must be defined by properties of its fundamental components, such as the
mode, that can be retrieved by the function “mode()” and the length by the function “length()”.
An empty vector can be created and may still have a mode

> v numeric()
> w character()

> mode(x)
[1] "numeric"
> mode(v)
[1] "numeric"
> mode(w)
[1] "character"
>
> length(x)
[1] 3

Step 5. Basic operations with numeric vectors


> x c(10, 20, 30)
>x
[1] 10 20 30
> 1/x
[1] 0.10000000 0.05000000 0.03333333

Step 6. A vector can be used in arithmetic expressions and/or as a combination of existing


vectors

> x c(10, 20, 30)


> y x*3+4
>y
[1] 34 64 94
> z c(x, 0, 0, 0, x)
>z
[1] 10 20 30 0 0 0 10 20 30
> w 2*x + y + z
>w
[1] 64 124 184 54 104 154 64 124 184

Note how the addition is sequential in this last case (value 1 of x is multiplied by 2, then added to
value 1 of y then added to value 1 of z, etc…)

Step 7. A vector can use built-in functions in R, such as mean() to calculate the mean of a
certain object (here x), var() to calculate its variance, and sort() to sort the content here of object
z.

> mean(x)
[1] 20
> var(x)
[1] 100
> sort(z)
[1] 0 0 0 10 10 20 20 30 30

Step 8. R uses built-in functions and operators to generate regular sequences. Here are examples
of how to use rep() to repeat items (arguments needed are the value to repeat and the number of
repeats) and seq() (arguments needed are the start, the end, and the interval) to create a sequence
of items.
> a c(1:10)
>a
[1] 1 2 3 4 5 6 7 8 9 10
> b rep(a, times=2)
>b
[1] 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10
> b rep(a, each=2)
>b
[1] 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 10 10
> c seq(-2, 2, by=.5)
>c
[1] -2.0 -1.5 -1.0 -0.5 0.0 0.5 1.0 1.5 2.0

Step 9. The content of a vector can be compared to another using basic operators

> x==x
[1] TRUE TRUE TRUE
> x==y
[1] FALSE FALSE FALSE
> x!=y
[1] TRUE TRUE TRUE

Step 10. The content of a Vector can be easily queried and modified. For this it is possible to use
Index Vectors to subset some elements of an existing vector, using square brackets

>x
[1] 10 20 30
> x[3]
[1] 30
> x[3] 50
>x
[1] 10 20 50
> length(x)
[1] 3

Step 11. For Index Vectors of character strings, a “names” attribute can help identify
components and query the data.

> dairy c(10, 20, 1, 40)


> names(dairy) c("milk", "butter", "cream", "yogurt")
> breakfast dairy[c("milk","yogurt")]
> breakfast
milk yogurt
10 40
Ex No
Date

3. Draw a histogram for any ungrouped frequency data.


Frequency Distributions, Histograms, Scatterplots, & Line Graphs
This document describes how to accomplish the following tasks.
Making a Frequency Table table(data) 2
Here we create a frequency table from raw data imported from a .CSV file. We also see how to append a
relative and cumulative frequency table to the original frequency table.
Making Histograms hist(data) 4
Here use the hist command to make a fast and dirty histogram and demonstrate how to add some bells
and whistles.
Using the plot command when the x-values are dates. Here we use the as.Date command to correctly
read dates.
• Entering Data
– Making a Data List (vector) list-name <- c(#, #, #, ..., #) 7
– Making a Table (matrix) table-name <- matrix( ....) 7
– Importing Data from a CSV File 8
table-name <- read.csv(file="file-name.csv", )
or
table-name <- read.table("File-Name.csv",header=TRUE,sep=",")
Frequency Tables in R: We took 42 test scores for male students and put the results into a frequency
table.

Then we created a relative and cumulative frequency table from this.


Here we see how to do these tasks with R. We’ll start by importing the data into R. Suppose the data is
in an Excel file saved as a .CSV file named Excel-Data.csv that looks like This is imported into R using
the read.table command.
> male female data <- read.table("Excel-Data.csv",header=TRUE,sep=",")
> male scores <- male female data$Males
Here we have R create a frequency table and then append a relative and cumulative table to it.
Everything in red is typed by the user. Everything in blue is output to the console.
– The classes are defined by creating a list of class boundaries. You can create this list by hand or
> bins <- seq(29.5,99.5,by=10)
The seq function creates a list by starting at 29.5 and increasing by 10 until it hits 99.5. Now bins =
[29.5, 39.5, 49.5, 59.5, 69.5, 79.5, 89.5, 99.5].
– The cut function organizes the data into the appropriate bins.
– The transform function puts the tables into column format - which is nice.
Here, we’ll let R create the histogram using the hist command. You can define your own classes by
creating a list of class boundaries and using the breaks = command. You can also add a title (main =), a
label (xlab =), and color (col =).
Ex No
Date

4. Fit a simple regression equation for a sample data and visualize using a
Scatter plot.
A scatter plot uses dots to represent values for two different numeric variables. Scatter plots are used to
observe relationships between variables. A linear regression is a straight line representation of
relationship between an independent and dependent variable. In this article, we will discuss how a scatter
plot with linear regression can be drafted using R and its libraries.

A scatter plot can be used to display all possible results and a linear regression plotted over it can be
used to generalize common characteristics or to derive maximum points that follow up a result. Here we
will first discuss the method of plotting a scatter plot and then draw a linear regression over it.
Salary Dataset
YearsExperience Salary
1.1 39343
1.3 46205
1.5 37731
2 43525
2.2 39891
2.9 56642
3 60150
3.2 54445
3.2 64445
3.7 57189
3.9 63218
4 55794
4 56957
4.1 57081
4.5 61111
4.9 67938
5.1 66029
5.3 83088
5.9 81363
6 93940
6.8 91738
7.1 98273
7.9 101302
8.2 113812
8.7 109431
9 105582
9.5 116969
9.6 112635
10.3 122391
10.5 121872

In R, function used to draw a scatter plot of two variables is plot() function which will return the scatter
plot.
Syntax: plot(x, y, main, xlab, ylab, xlim, ylim, axes)
Parameters:-
x- is the data set whose values are the horizontal coordinates.
y- is the data set whose values are the vertical coordinates.
main- is the tile of the graph.
xlab- is the label on the horizontal axis.
ylab- is the label on the vertical axis.
xlim- is the limits of the values of x used for plotting.
ylim- is the limits of the values of y used for plotting.
axes- indicates whether both axes should be drawn on the plot.
Return:-

A 2-Dimension scatter plot.


Program:
library(readxl)

# import data
Salary_Data <- read_excel("Salary_Data.xls")

# plot scatter plot


plot(Salary_Data$YearsExperience,Salary_Data$Salary,
main='YearsExperience Vs Salary',
xlab='YearsExperience', ylab='Salary')
A regression line is a straight line that describes how a response variable y(Dependent variable) changes
as an explanatory variable x(Independent)changes. This is used to predict the value of y for a given value
of x.

For drawing regression line we need two functions:


abline() function is used to add one or more straight lines through the current plo
plot
Syntax: abline(a=NULL, b=NULL, h=NULL, v=NULL, … …)
Parameters:
a, b: It specifies the intercept and the slope of the lin
line
h: specifies y-value for horizontall line(s
line(s)
v: specifies x-value(s)
value(s) for vertical line(s
line(s)
Returns: a straight line in the plot
lm() function which stands for linear model,” function can be used to create a simple regression model.
model
Syntax: lm(formula,data)
Parameters:
the formula- is a symboll presenting the relation between x and yy.
data- is the vector on which the formula will be applied
applied.
Returns:
The relationship line of x and y.
Program:
library(readxl)
# import data
Salary_Data <- read_excel("Salary_Data.xls")
# plot a scatter plot
plot(Salary_Data$YearsExperience,Salary_Data$Salary,
main='Regression for YearsExperience and Salary',
xlab='YearsExperience',ylab='Salary')
# plot a regression line
abline(lm(Salary~YearsExperience,data=Salary_Data),col='red')
Ex No
Date

5. Demonstrate the one sample t test.


One Sample T-Test in R
The One Sample t-test, or student’s test, compares the mean of a vector against a theoretical mean, One
Sample T-Test in R. The formula used to compute the t-test is:

Here,

m refers to the mean


µ to the theoretical mean
s is the standard deviation
n the number of observations.
To evaluate the statistical significance of the t-test, you need to compute the p-value. The p-value ranges
from 0 to 1, and is interpreted as follow:
A p-value lower than 0.05 means you are strongly confident to reject the null hypothesis, thus H3 is
accepted.
A p-value higher than 0.05 indicates that you don’t have enough evidences to reject the null hypothesis.
You can construct the p-value by looking at the corresponding absolute value of the t-test in the Student
distribution with a degrees of freedom equals to One Sample T-Test in R
For instance, if you have 5 observations, you need to compare our t-value with the t-value in the Student
distribution with 4 degrees of freedom and at 95 percent confidence interval. To reject the null
hypothesesis, the t-value should be higher than 2.77.
In R, we use the following syntax of t.test() function for performing a one-sample T-test in R.
t.test(x, ?=0)
Here,
1. x is the name of our variable of interest.
2. ? is described by the null hypothesis, which is set equal to the mean.

Let's see an example of One-Sample T-test in which we test whether the volume of a shipment of wood
was less than usual(?0=0).

set.seed(0)
ship_vol <- c(rnorm(70, mean = 35000, sd = 2000))
t.test(ship_vol, mu = 35000)
Output:
Ex No
Date

6. Demonstrate the two sample t test


As previously stated, two-sample t-tests are used when you want to compare two different
samples. In order to do this in R, you can use t.test or pairwise.t.test. This section will focus
on t.test.

Unpaired t-Test
The unpaired t-test is used when you want to compare two independent groups.
Suppose we want to test if the average increased sleep with two different drugs are equal, using
the sleep dataset and t.test function.
t.test(extra~group, data = sleep)
##
## Welch Two Sample t-test
##
## data: extra by group
## t = -1.8608, df = 17.776, p-value = 0.07939
## alternative hypothesis: true difference in means is not equal to 0
## 95 percent confidence interval:
## -3.3654832 0.2054832
## sample estimates:
## mean in group 1 mean in group 2
## 0.75 2.33
As you can see, t.test outputs all of the information you need for a two-sample t-test. The p-
value, alternative hypothesis (H ), confidence interval around the true difference in means, and
1

the sample averages of each group, just to name a few. Notice that the p-value is > 0.05,
implying that there does not exist enough evidence to reject the null; that is, the two groups are
not statistically different.
You can also save the result of t.test and use the $ operator to extract the results, like so:
sleep_unpaired <- t.test(extra~group, data = sleep)
sleep_unpaired$p.value
## [1] 0.07939414

Paired t-Test
Use paired t-tests when obervations from one group are paired with the other. This can be done
easily in R, by simply adding paired = TRUE when calling t.test and/or pairwise.t.test.
t.test(extra~group, data = sleep, paired = TRUE)
##
## Paired t-test
##
## data: extra by group
## t = -4.0621, df = 9, p-value = 0.002833
## alternative hypothesis: true difference in means is not equal to 0
## 95 percent confidence interval:
## -2.4598858 -0.7001142
## sample estimates:
## mean of the differences
## -1.58
If you compare the results of the paired test with the unpaired, you may notice that the p-values
are different: 0.079 for the unpaired test and 0.003 for the paired. Why is this?
Even though the two methods are comparing group means, they are looking at the data in
different ways. Just look at how the test statistics are computed. For unpaired tests, the test
statistic is calculated as follows:
tunpaired=x¯1−x¯2s2(1n1+1n2)−−−−−−−−−−√tunpaired=x¯1−x¯2s2(1n1+1n2)
Where x¯ix¯i is the mean of group i, nini is the sample size of group i, and s2s2 is the pooled
variance.
For paired tests, the test statistic is calculated as follows:
tpaired=d¯sdn√tpaired=d¯sdn
where d¯d¯ is the mean difference between observations (yi−xiyi−xi), sdsd is the standard
deviation of the differences, and nn is the sample size.
The unpaired test compares group means idependently. However, when utilizing paired t-tests,
the observations are not independent and so tests the mean difference to determine if there is a
signficant difference between treatments.
Ex No
Date

7. PLOT function to create graphs in R.


The plot() function is used to draw points (markers) in a diagram.
The function takes parameters for specifying points in the diagram.
Parameter 1 specifies points on the x-axis.
Parameter 2 specifies points on the y-axis.
At its simplest, you can use the plot() function to plot two numbers against each other:
plot(1, 3)

Draw two points in the diagram, one at position (1, 3) and one in position (8, 10):

plot(c(1, 8), c(3, 10))

Multiple Points
You can plot as many points as you like, just make sure you have the same number of points in both
axis:

Example
plot(c(1, 2, 3, 4, 5), c(3, 7, 8, 9, 12))
For better organization, when you have many values, it is better to use variables:

Example
x <- c(1, 2, 3, 4, 5)
y <- c(3, 7, 8, 9, 12)

plot(x, y)

Sequences of Points
If you want to draw dots in a sequence, on both the x-axis and the y-axis, use the : operator:

Example
plot(1:10)

Draw a Line
The plot() function also takes a type parameter with the value l to draw a line to connect all the points in
the diagram:

Example
plot(1:10, type="l")

Plot Labels
The plot() function also accept other parameters, such as main, xlab and ylab if you want to customize
the graph with a main title and different labels for the x and y-axis:

Example
plot(1:10, main="My Graph", xlab="The x-axis", ylab="The y axis")

Graph Appearance
There are many other parameters you can use to change the appearance of the points.

Colors
Use col="color" to add a color to the points:

Example
plot(1:10, col="red")
Size
Use cex=number to change the size of the points (1 is default, while 0.5 means 50% smaller, and 2
means 100% larger):

Example
plot(1:10, cex=2)

Point Shape
Use pch with a value from 0 to 25 to change the point shape format:

Example
plot(1:10, pch=25, cex=2)

The values of the pch parameter ranges from 0 to 25, which means that we can choose up to 26 different
types of point shapes:
A line graph has a line that connects all the points in a diagram.

To create a line, use the plot() function and add the type parameter with a value of "l":

Example
plot(1:10, type="l")

Line Color
The line color is black by default. To change the color, use the col parameter:

Example
plot(1:10, type="l", col="blue")

Line Width
To change the width of the line, use the lwd parameter (1 is default, while 0.5 means 50% smaller, and 2
means 100% larger):

Example
plot(1:10, type="l", lwd=2)

Line Styles
The line is solid by default. Use the lty parameter with a value from 0 to 6 to specify the line format.

For example, lty=3 will display a dotted line instead of a solid line:

Example
plot(1:10, type="l", lwd=5, lty=3)

Multiple Lines
To display more than one line in a graph, use the plot() function together with the lines() function:

Example
line1 <- c(1,2,3,4,5,10)
line2 <- c(2,5,7,8,9,10)
plot(line1, type = "l", col = "blue")
lines(line2, type="l", col = "red")
Ex No
Date

Usage of 3D plot in R.

3D plot in R Language is used to add title, change viewing direction, and add color and shade to the plot.
The persp() function which is used to create 3D surfaces in perspective view. This function will draw
perspective plots of a surface over the x–y plane. persp() is defines as a generic function. Moreover, it
can be used to superimpose additional graphical elements on the 3D plot, by lines() or points(), using the
function trans3d().

persp() Function in R Programming Language


Syntax: persp(x, y, z)

Parameter: This function accepts different parameters i.e. x, y and z where x and y are vectors defining
the location along x- and y-axis. z-axis will be the height of the surface in the matrix z.

Return Value: persp() returns the viewing transformation matrix for projecting 3D coordinates (x, y, z)
into the 2D plane using homogeneous 4D coordinates (x, y, z, t).

Example 1: Simple Right Circular Cone

# To illustrate simple right circular cone


cone <- function(x, y){
sqrt(x ^ 2 + y ^ 2)
}

# prepare variables.
x <- y <- seq(-1, 1, length = 30)
z <- outer(x, y, cone)

# plot the 3D surface


persp(x, y, z)
Here in the above code, function seq() to generate a vector of equally spaced numbers. The outer()
function to apply the function cone at every combination of x and y.

Example 2: Adding Titles and Labeling Axes to Plot


# Adding Titles and Labeling Axes to Plot
cone <- function(x, y){
sqrt(x ^ 2 + y ^ 2)
}

# prepare variables.
x <- y <- seq(-1, 1, length = 30)
z <- outer(x, y, cone)

# plot the 3D surface


# Adding Titles and Labeling Axes to Plot
persp(x, y, z,
main="Perspective Plot of a Cone",
zlab = "Height",
theta = 30, phi = 15,
col = "orange", shade = 0.4)
Example 3: Visualizing a simple DEM(Digital elevation model)
# Visualizing a simple DEM model

z <- 2 * volcano # Exaggerate the relief


x <- 10 * (1:nrow(z)) # 10 meter spacing (S to N)
y <- 10 * (1:ncol(z)) # 10 meter spacing (E to W)

# Don't draw the grid lines : border = NA


par(bg = "gray")
persp(x, y, z, theta = 135, phi = 30,
col = "brown", scale = FALSE,
ltheta = -120, shade = 0.75,
border = NA, box = FALSE)

You might also like