R Programming Lab
R Programming Lab
Description:
Method: 1
An empty data frame can also be created with or without specifying the column
names and column types to the data values contained within it. data.frame() method can be
used to create a data frame, and we can assign the column with the empty vectors. Column
type checking with zero rows is supported by the data frames, where in we define the data
type of each column prior to its creation.
Source Code:
df=data.frame(Ints=integer(),
Doubles=double(),
Characters=character(),
Logicals=logical(),
Factors=factor(),
stringsAsFactors=FALSE)
print("Structure of the empty dataframe:")
print(str(df))
Output:
12. Aim: Write a R program to create a data frame from four given vectors.
Description:
In this aprogram we will see how to create a Dataframe from four given vectors in
R. To create a data frame in R using the vector, we must first have a series of vectors
containing data. The data.frame() function is used to create a data frame from vector in R.
Syntax:data.frame(vectors)
Source Code:
name = c('Divya', 'Rani', 'Pavan', 'Surya', 'Ambika')
score = c(82.5, 90, 86.5, 95, 92)
attempts = c(1, 3, 2, 3, 2)
qualify = c('yes', 'no', 'yes', 'no', 'Yes')
print("Original data frame:")
df = data.frame(name, score, attempts, qualify)
print(df)
Output:
>name = c('Divya', 'Rani', 'Pavan', 'Surya', 'Ambika')
>score = c(82.5, 90, 86.5, 95, 92)
>attempts = c(1, 3, 2, 3, 2)
> qualify = c('yes', 'no', 'yes', 'no', 'Yes')
>print("Original data frame:")
[1] "Original data frame:"
>
>df = data.frame(name, score, attempts, qualify)
>print(df)
name score attempts qualify
1 Divya 82.5 1 yes
2 Rani 90.0 3 no
3 Pavan 86.5 2 yes
4 Surya 95.0 3 no
5 Ambika 92.0 2 Yes
OR
12. Aim: Write a R program to create a data frame using two given vectors and display the
duplicated elements and unique rows of the said data frame.
Description:
A data frame is used for storing data tables which has a list of vectors with equal
length. The data frames are created by function data.frame(), which has tightly coupled
collections of variables. The syntax of this function is,
Where dots(...) indicates the arguments are of either the form value or tag = value
and row. name is a NULL or a single integer or character string.
Below are the steps used in the R program to create a data frame using two given vectors
and display the duplicated elements and unique rows. In this R program, we directly give the data
frame to a built-in function. Here we are using variables v1,v2 for holding different types of
vectors, and V for holding created data frame. Call the function data.frame() for
creating dataframe. For getting duplicate elements call the method like duplicated(v1v2) and
for getting unique elements call it like unique(v1v2).
ALGORITHM
STEP 1: Assign variables v1,v2 with vector values and V for data frame
STEP 2: First print original vector values
STEP 3: Create a data frame from given vectors as data.frame(v1,v2)
STEP 4: Print the duplicate elements by calling duplicated(v1v2)
STEP 5: Print the unique elements by calling unique(v1v2)
Sorce Code:
a = c(10,20,10,10,40,50,20,30)
b = c(10,30,10,20,0,50,30,30)
print("Original data frame:")
ab = data.frame(a,b)
print(ab)
print("Duplicate elements of the said data frame:")
print(duplicated(ab))
print("Unique rows of the said data frame:")
print(unique(ab))
Output:
> a = c(10,20,10,10,40,50,20,30)
> b = c(10,30,10,20,0,50,30,30)
>print("Original data frame:")
[1] "Original data frame:"
>ab = data.frame(a,b)
>print(ab)
a b
1 10 10
2 20 30
3 10 10
4 10 20
5 40 0
6 50 50
7 20 30
8 30 30
>print("Duplicate elements of the said data frame:")
[1] "Duplicate elements of the said data frame:"
>print(duplicated(ab))
[1] FALSE FALSE TRUE FALSE FALSEFALSE TRUE FALSE
>print("Unique rows of the said data frame:")
[1] "Unique rows of the said data frame:"
>print(unique(ab))
a b
1 10 10
2 20 30
4 10 20
5 40 0
6 50 50
8 30
13) Aim: Write a R program to create a matrix from a list of given vectors.
Description:
In R programming language, vector is a basic object which consists of
homogeneous elements. The data type of vector can be integer, double, character, logical,
complex or raw. A vector can be created by using c() function.
Syntax:
x <- c(val1, val2, .....)
Vectors in R are the same as the arrays in C language which are used to hold
multiple data values of the same type. Vectors can also be used to create matrices.
Matrices can be created with the help of Vectors by using pre-defined functions in R
Programming Language. These functions take vectors as arguments along with several
other arguments for matrix dimensions, etc.
Functions used for Matrix creation:
matrix() function
cbind() function
rbind() function
Source Code:
l =list()
for(iin1:5) l[[i]]<- c(i,1:4)
print("List of vectors:")
print(l)
result=do.call(rbind, l)
print("New Matrix:")
print(result)
Output:
> l = list()
>for (i in 1:5) l[[i]] <- c(i, 1:4)
>print("List of vectors:")
[1] "List of vectors:"
>print(l)
[[1]]
[1] 1 1 2 3 4
[[2]]
[1] 2 1 2 3 4
[[3]]
[1] 3 1 2 3 4
[[4]]
[1] 4 1 2 3 4
[[5]]
[1] 5 1 2 3 4
>result = do.call(rbind, l)
>print("New Matrix:")
[1] "New Matrix:"
>print(result)
[,1] [,2] [,3] [,4] [,5]
[1,] 1 1 2 3 4
[2,] 2 1 2 3 4
[3,] 3 1 2 3 4
[4,] 4 1 2 3 4
[5,] 5 1 2 3 4
>
14) Aim: Write a R program to concatenate two given matrices of same column but
different rows.
Description:
Given two matrices A and B of size M x N, the task is to concatenate them into one matrix.
Concatenation of matrix: The process of appending elements of every row of the matrix
one after the other is known as the Concatenation of matrix.
Examples:
Input:
A[][] = {{1, 2},
{3, 4}},
B[][] = {{5, 6},
{7, 8}}
Output:
1256
3478
Explanation:
Elements of every row of the matrix B
is appended into the row of matrix A.
Source Code:
x = matrix(1:12, ncol=3)
y = matrix(13:24, ncol=3)
print("Matrix-1")
print(x)
print("Matrix-2")
print(y)
result = dim(rbind(x,y))
print("After concatenating two given matrices:")
print(result)
Output:
[1] "Matrix-1"
[,1] [,2] [,3]
[1,] 1 5 9
[2,] 2 6 10
[3,] 3 7 11
[4,] 4 8 12
[1] "Matrix-2"
[,1] [,2] [,3]
[1,] 13 17 21
[2,] 14 18 22
[3,] 15 19 23
[4,] 16 20 24
[1] "After concatenating two given matrices:"
[1] 8 3
15) Write a R program to find row and column index of maximum and minimum value
in a given matrix.
Description:
Finding Maximum value:
In the code below, we have created a sample matrix, in which we have passed
“nrow=3“(matrix will have only 3 rows) in example 1 and “ncol=2“(matrix will have
only 2 columns) in example 2.
Then we have printed the sample matrix in the next line with the message “Sample
Matrix”.
Then we have used the syntax below to find the row and column number of the
maximum element and stored it in the variable “max”. We have made use of the max()
function which is used to find the maximum element present in an object. This
object can be a Vector, a list, a matrix, a data frame, etc.
The “which()” function is used to get the index or position of the value which
satisfies the given condition. Then we have printed the maximum value along with its
row and column index.
Syntax: which(m == max(m), arr.ind=TRUE)
Finding Minimum value:
In the code below, we have created a sample matrix, in which we have passed
“nrow=3“(matrix will have only 3 rows) in example 1 and “ncol=8“(matrix will have
only 8 columns) in example 2 as a parameter while defining the matrix.
Then we have printed the sample matrix in the next line with the message “Sample
Matrix”.
Then we have used the syntax below to find the row and column number of the
minimum element and stored it in the variable “min”. We have made use of the min()
function which is used to find the minimum element present in an object. This
object can be a Vector, a list, a matrix, a data frame, etc.
The “which()” function is used to get the index or position of the value which
satisfies the given condition. Then we have printed the minimum value along with its
row and column index.
Syntax: which(m == min(m), arr.ind=TRUE)
Source Code:
# defining a sample matrix
m = matrix(c(11, 20, 13, -9, 1, 99, 36, 81, 77), nrow = 3)
print("Sample Matrix:")
print(m)
# stores indexes of min value
min = which(m == min(m), arr.ind = TRUE)
print(paste("Minimum value: ", m[min]))
print(min)
Output:
[1] "Sample Matrix:"
[,1] [,2] [,3]
[1,] 11 -9 36
[2,] 20 1 81
[3,] 13 99 77
[1] "Minimum value: -9"
row col
[1,] 1 2
Syntax:c()
Source Code:
vector= c()
values = c(0,1,2,3,4,5,6,7,8,9)
for(iin1:length(values))
vector[i]<- values[i]
print(vector)
Output:
[1] 0 1 2 3 4 5 6 7 8 9
17) Aim: Write a R program to multiply two vectors of integers type and length 3.
Description:
To write an R program to multiply two vectors. We can give two vector values to calculate
the multiplication. For the calculation of vector product here we use the product(*)
operator.Given below are the steps which are used in the R program to multiply two vectors.
In this R program, we accept the vector values into variables A and B. The result value of
vectors is assigned variable C.Finally the variable C is printed as output vector.
ALGORITHM
STEP 1: take the two vector values into the variables A,B
STEP 2: Consider C as the result vector
STEP 3: Calculate the vector product using the * operator
STEP 4: First print the original vectors
STEP 5: Assign the result of product value to vector C as C=A*B
STEP 6: print the vector C as result vector
Source Code:
x = c(10, 20, 30)
y = c(20, 10, 40)
print("Original Vectors:")
print(x)
print(y)
print("Product of two Vectors:")
z=x/y
u=x*y
print(z)
print(u)
Output:
[1] "Original Vectors:"
[1] 10 20 30
[1] 20 10 40
[1] "Product of two Vectors:"
[1] 0.50 2.00 0.75
[1] 200 200 1200
18) Write a R program to find Sum, Mean and Product of a Vector, ignore element like
NA or NaN.
Description:
sum(), mean(), and prod() methods are available in R which are used to compute the
specified operation over the arguments specified in the method. In case, a single vector is
specified, then the operation is performed over individual elements, which is equivalent to
the application of for loop.
Function Used:
mean() function is used to calculate mean
Syntax: mean(x, na.rm)
Parameters:
x: Numeric Vector
na.rm: Boolean value to ignore NA value
Source Code:
print("Sum:")
print(sum(x, na.rm=TRUE))
print("Mean:")
print(mean(x, na.rm=TRUE))
print("Product:")
print(prod(x, na.rm=TRUE))
Output:
[1] "Sum:"
[1] 60
[1] "Mean:"
[1] 20
[1] "Product:"
[1] 6000
19) Write a R program to list containing a vector, a matrix and a list and give names to
the elements in the list.
Description:
Lists are the R objects which contain elements of different types like − numbers,
strings, vectors and another list inside it. A list can also contain a matrix or a function as its
elements. List is created using list() function.
Creating a List
Following is an example to create a list containing strings, numbers, vectors and a logical
values.
Source Code:
list_data<-list(c("Red","Green","Black"), matrix(c(1,3,5,7,9,11),nrow=2),
list("Python","PHP","Java"))
print("List:")
print(list_data)
names(list_data)= c("Color","Odd numbers","Language(s)")
print("List with column names:")
print(list_data)
Output:
[1] "List:"
[[1]]
[1] "Red" "Green" "Black"
[[2]]
[,1] [,2] [,3]
[1,] 1 5 9
[2,] 3 7 11
[[3]]
[[3]][[1]]
[1] "Python"
[[3]][[2]]
[1] "PHP"
[[3]][[3]]
[1] "Java"
$`Odd numbers`
[,1] [,2] [,3]
[1,] 1 5 9
[2,] 3 7 11
$`Language(s)`
$`Language(s)`[[1]]
[1] "Python"
$`Language(s)`[[2]]
[1] "PHP"
$`Language(s)`[[3]]
[1] "Java"
20) Aim: Write a R program to create a list containing a vector, a matrix and a list and
remove the second element.
Description:
We can add, delete and update list elements as shown below. We can add and delete elements
only at the end of a list. But we can update any element.
Live Demo
# Create a list containing a vector, a matrix and a list.
list_data<- list(c("Jan","Feb","Mar"), matrix(c(3,9,5,1,-2,8),nrow=2),
list("green",12.3))
[[2]]
[,1] [,2] [,3]
[1,] 1 5 9
[2,] 3 7 11
[[3]]
[[3]][[1]]
[1] "Python"
[[3]][[2]]
[1] "PHP"
[[3]][[3]]
[1] "Java"
[[2]]
[[2]][[1]]
[1] "Python"
[[2]][[2]]
[1] "PHP"
[[2]][[3]]
[1] "Java"
21) Aim: Write a R program to select second element of a given nested list.
Description:
To select the second element of a given nested list. Here we are using a built-in
function lapply() for this. Usually, in programming languages, we use loops for this type
of program. There are different types of apply() functions are available to work on lists,
vectors, and data frames, also they can be viewed as substitutes to the loop
constructs. lapply() is one of them and ' l ' stands for list. This function helps to perform
some operations on list objects and return a list of the same length as the list object given as
an argument. The return list will be the result of applying FUN to the corresponding elements
of X . The syntax of this function is
Syntax:lapply(X, FUN, …)
Where X is a vector (atomic or list) or an expression object and FUN is the function
to be applied to each element of X
ALGORITHM
STEP 1: Assign variable values_lst with a nested list
STEP 3: Call the apply function as lapply(values_lst, '[[', 2) for finding the second element of
each list
Source Code:
x =list(list(0,2),list(3,4),list(5,6))
print("Original nested list:")
print(x)
e =lapply(x,'[[',2)
print("Second element of the nested list:")
print(e)
Output:
[1] "Original nested list:"
[[1]]
[[1]][[1]]
[1] 0
[[1]][[2]]
[1] 2
[[2]]
[[2]][[1]]
[1] 3
[[2]][[2]]
[1] 4
[[3]]
[[3]][[1]]
[1] 5
[[3]][[2]]
[1] 6
[[2]]
[1] 4
[[3]]
[1] 6
22) Aim: Write a R program to create a list named s containing sequence of 15 capital
letters, starting from ‘E’.
Description:
Return all upper case letters using LETTERS function
We will get all letters in uppercase sequence by using LETTERS function.
Syntax:
LETTERS
Subsequence letters using range operation
We can get the subsequence of letters using the index. Index starts with 1 and ends with 26
(since there are 26 letters from a to z). We are getting from letters/LETTERS function.
Syntax:
letters[start:end]
LETTERS[start:end]
Source Code:
l =LETTERS[match("E", LETTERS):(match("E", LETTERS)+15)]
print("Content of the list:")
print("Sequence of 15 capital letters, starting from ‘E’-")
print(l)
Output:
[1] "Content of the list:"
[1] "Sequence of 15 capital letters, starting from ‘E’-"
[1] "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q" "R" "S" "T"
----------------------------------------------------------------------------------------------------------------
23) Aim: Write a R program to assign new names "a", "b" and "c" to the elements of a
given list.
Description:
A list is an object in R Language which consists of heterogeneous elements. A list
can even contain matrices, data frames, or functions as its elements. The list can be created
using list() function in R. Named list is also created with the same function by specifying
the names of the elements to access them. Named list can also be created
using names() function to specify the names of elements after defining the list.
Syntax: names(x) <- value
Parameters:
x: represents an R object
value: represents names that has to be given to elements of x object
Source Code:
list1 =list(g1 =1:10, g2 ="R Programming", g3 ="HTML")
print("Original list:")
print(list1)
names(list1)= c("one","two","three")
print("Assign new names 'one', 'two' and 'three' to the elements of the said list")
print(list1)
Output:
[1] "Original list:"
$g1
[1] 1 2 3 4 5 6 7 8 9 10
$g2
[1] "R Programming"
$g3
[1] "HTML"
[1] "Assign new names 'one', 'two' and 'three' to the elements of the said list"
$one
[1] 1 2 3 4 5 6 7 8 9 10
$two
[1] "R Programming"
$three
[1] "HTML"
----------------------------------------------------------------------------------------------------------------
24) Aim: Write a R program to create an ordered factor from data consisting of the
names of months.
Description:
R – Level Ordering of Factors
Factors are data objects used to categorize data and store it as levels. They can store
a string as well as an integer. They represent columns as they have a limited number of
unique values. Factors in R can be created using factor() function. It takes a vector as
input. c() function is used to create a vector with explicitly provided values.
Source Code:
mons_v = c("March","April","January","November","January",
"September","October","September","November","August","February",
"January","November","November","February","May","August","February",
"July","December","August","August","September","November","September",
"February","April")
print("Original vector:")
print(mons_v)
f = factor(mons_v)
print("Ordered factors of the said vector:")
print(f)
print(table(f))
Output:
[1] "Original vector:"
[1] "March" "April" "January" "November" "January" "September"
[7] "October" "September" "November" "August" "February" "January"
[13] "November" "November" "February" "May" "August" "February"
[19] "July" "December" "August" "August" "September" "November"
[25] "September" "February" "April"
[1] "Ordered factors of the said vector:"
[1] March April January November January September October
[8] September November August February January November November
[15] February May August February July December August
[22] August September November September February April
11 Levels: April August December February January July March May ... September
f
April August December February January July March May
2 4 1 4 3 1 1 1
November October September
5 1 4
25) Aim: Write a R program to concatenate two given factor in a single factor.
Description:
Below are the steps used in the R program to concatenate two given factors into a
single factor. In this R program, we directly give the values to built-in functions. And print
the function result. Here we used two variables namely fact1 and fact2 for assigning factor
values. The third variable fact contains the concatenated factor and finally prints the resulting
factor.
ALGORITHM
STEP 1: Assign variable fact1,fact2 with factor values
STEP 2: First print original factors values
STEP 3:Call the built-in function factor with level as factor(c(levels(fact1)[fact1],
levels(fact2)[fact2]))
STEP 4: Assign variable fact with the function result
STEP 5: Print the concatenated factor
Source Code:
f1 <-factor(sample(LETTERS, size=6, replace=TRUE))
f2 <-factor(sample(LETTERS, size=6, replace=TRUE))
print("Original factors:")
print(f1)
print(f2)
f = factor(c(levels(f1)[f1], levels(f2)[f2]))
print("After concatenate factor becomes:")
print(f)
Output:
[1] "Original factors:"
[1] Q V O P L B
Levels: B L O P Q V
[1] Z H V Y S K
Levels: H K S V Y Z
[1] "After concatenate factor becomes:"
[1] Q V O P L B Z H V Y S K
Levels: B H K L O P Q S V Y Z
LIST OF EXPERIMENTS:
1) Write a R program to take input from the user (name and age) and display the
values. Also print the version of R installation.
3) Write a R program to create a sequence of numbers from 20 to 50 and find the mean
of numbers from 20 to 60 and sum of numbers from 51 to 91.
5) Write a R program to get the unique elements of a given string and unique numbers
of vector.
6) Write a R program to create three vectors a,b,c with 3 integers. Combine the three
vectors to become a 3×3 matrix where each column represents a vector. Print the
content of the matrix.
7) Write a R program to create a 5 x 4 matrix , 3 x 3 matrix with labels and fill the
matrix by rows and 2 × 2 matrix with labels and fill the matrix by columns.
8) Write a R program to combine three arrays so that the first row of the first array is
followed by the first row of the second array and then first row of the third array.
10) Write a R program to create an array using four given columns, three given rows,
and two given tables and display the content of the array.
12) Write a R program to create a data frame from four given vectors.
13) Write a R program to create a data frame using two given vectors and display the
duplicated elements and unique rows of the said data frame.
14) Write a R program to save the information of a data frame in a file and display the
information of the file.
16) Write a R program to concatenate two given matrices of same column but different
rows.
17) Write a R program to find row and column index of maximum and minimum value
in a given matrix.
19) Write a R program to multiply two vectors of integers type and length 3.
20) Write a R program to find Sum, Mean and Product of a Vector, ignore element like
NA or NaN.
21) Write a R program to list containing a vector, a matrix and a list and give names to
the elements in the list.
22) Write a R program to create a list containing a vector, a matrix and a list and give
names to the elements in the list. Access the first and second element of the list.
23) Write a R program to create a list containing a vector, a matrix and a list and
remove the second element.
25) Write a R program to merge two given lists into one list.
26) Write a R program to create a list named s containing sequence of 15 capital letters,
starting from ‘E’.
27) Write a R program to assign new names "a", "b" and "c" to the elements of a
given list.
29) Write a R program to create an ordered factor from data consisting of the names of
months.