R Programming Cse I & II
R Programming Cse I & II
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.
ALGORITHM
STEP 2: print the user input along with other text with the help of paste()
Source Code
name = readline(prompt="Input your name: ")
age = readline(prompt="Input your age: ")
print(paste("My name is",name, "and I am",age ,"years old."))
print(R.version.string)
Output:
values
STEP 4: Call the built-in functions ls.str() for string based long listing
Source Code
name = "Python";
num1 = 8;
num2 = 1.5
nums = c(10, 20, 30, 40, 50, 60)
print(ls())
print("Details of the objects in memory:")
print(ls.str())
OUTPUT
[1] "num1" "num2" "name" "nums"
num1 : num 8
ALGORITHM
STEP 1: Use the built-in functions
STEP 2: call seq() with two values from and to specifying the limit of
sequence values
STEP 3: call mean() with two values from and to specifying the limit of
numbers
STEP 4: call sum() with two values from and to specifying the limit of
numbers
Source Code:
Output:
[1] 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
36 37 38 39 40
[1] "Mean of numbers from 20 to 60:"
[1] 40
[1] "Sum of numbers from 51 to 91:"
[1] 2911
4. Write a R program to create a simple bar plot of five subjects marks.
Source Code:
Output:
5. Write a R program to get the unique elements of a given string and
unique numbers of vector.
Here we are using a built-in function unique() for this finding. This function
helps to find the distinct or unique values from the vector by eliminating
duplicate values. The syntax of this function is
unique(x)
Here x is the vector, matrix, or data frame, returns a similar object whose
duplicate elements need to be eliminated.
ALGORITHM
STEP 1: Assign variable A with vector values
Source Code:
str1 = "The quick brown fox jumps over the lazy dog."
print("Original vector(string)")
print(str1)
print("Unique elements of the said vector:")
print(unique(tolower(str1)))
nums = c(1, 2, 2, 3, 4, 4, 5, 6)
print("Original vector(number)")
print(nums)
print("Unique elements of the said vector:")
print(unique(nums))
Output:
ALGORITHM
STEP 1: Assign variables a,b and c with vector values
Source Code:
a<-c(1,2,3)
b<-c(4,5,6)
c<-c(7,8,9)
print("Original vectors:")
print(a)
print(b)
print(c)
m<-cbind(a,b,c)
print("Content of the said matrix:")
print(m)
Output:
Here we are using a built-in function matrix() for this conversion. This
method helps to creates a matrix from the given set of values. The syntax of
this function is,
byrow: If FALSE (the default) the matrix is filled by columns, otherwise filled
by rows.
dimnames: NULL or a list of length 2 giving the row and column names
respectively.
Source Code:
Output:
The t() method is then applied over the result to create a transpose of the obtained output. The
rows and columns are then reversed to produce a transpose matrix. The matrix operation is
then applied over the output, where
Source Code:
num1 = rbind(rep("A",3), rep("B",3), rep("C",3))
print("num1")
print(num1)
num2 = rbind(rep("P",3), rep("Q",3), rep("R",3))
print("num2")
print(num2)
num3 = rbind(rep("X",3), rep("Y",3), rep("Z",3))
print("num3")
print(num3)
a = matrix(t(cbind(num1,num2,num3)),ncol=3, byrow=T)
print("Combine three arrays, taking one row from each one by one:")
print(a)
Output:
[1] "num1"
[,1] [,2] [,3]
[1,] "A" "A" "A"
[2,] "B" "B" "B"
[3,] "C" "C" "C"
[1] "num2"
[,1] [,2] [,3]
[1,] "P" "P" "P"
[2,] "Q" "Q" "Q"
[3,] "R" "R" "R"
[1] "num3"
[,1] [,2] [,3]
[1,] "X" "X" "X"
[2,] "Y" "Y" "Y"
[3,] "Z" "Z" "Z"
[1] "Combine three arrays, taking one row from each
one by one:"
[,1] [,2] [,3]
[1,] "A" "A" "A"
[2,] "P" "P" "P"
[3,] "X" "X" "X"
[4,] "B" "B" "B"
[5,] "Q" "Q" "Q"
[6,] "Y" "Y" "Y"
[7,] "C" "C" "C"
[8,] "R" "R" "R"
[9,] "Z" "Z" "Z"
9. Write a R program to create a two-dimensional 5x3 array of sequence of even integers
greater than 50.
Algorithm:
Source Code:
Output:
To create an array using given columns, rows, and tables in R Programming Language. The
array is created using the array() function.
Syntax: Array(vector.., dim=c(row, columns, tables))
Parameter:
• x: vector
• dim: values used to create array
Source Code:
v1 = c(1, 3, 5, 7, 4)
v2 = c(2, 4, 6, 8, 10)
print(arra1)
Output:
, , 1
, , 2
The following steps used in the R program to create an empty data frame. In this
R program, we directly give the values to the built-in function. And print the
function result. Here we used the variable Df is used as a data frame. The data
frame consists of different data types which are integer, Doubles, Characters,
Logical, Factors, StringsAs Factors.
ALGORITHM
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
[1] "Structure of the empty dataframe:"
$ Ints : int
$ Doubles : num
$ Characters: chr
$ Logicals : logi
NULL
12.Write a R program to create a data frame from four given vectors.
To create a data frame from four given vectors. We can use a built-in
collections of variables.
Where dots(...) indicates the arguments are of either the form value or tag =
The following steps are used in the R program to create a data frame
from four given vectors. In this R program, we directly give the data frame to a
built-in function. Here we are using variables contestant, points, tries, win for
Source Code
contestant = c('John', 'Michael', 'Albert', 'James', 'Kevin')
points= c(10, 9.2, 14, 12.5,18)
tries = c(1, 3, 2, 3, 2)
win= c('yes', 'no', 'yes', 'no', 'no')
print("Original data frame:")
print(contestant)
print(points)
print(tries)
print(win)
df = data.frame(contestant,points,tries,win)
print(df)
OUTPUT
[1] "Original data frame:"
[1] 1 3 2 3 2
2 Michael 9.2 3 no
4 James 12.5 3 no
5 Kevin 18.0 2 no
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.
To create a data frame using two given vectors and display the duplicated elements and unique
rows, we are using a built-in function data.frame() for this. 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.
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.
The following steps are 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
v1 = c(10,20,10,10,40,50,20,30)
v2= c(10,30,10,20,0,50,30,30)
print("Original data frame:")
V = data.frame(v1,v2)
print(v1v2)
print("Duplicate elements of the data frame:")
print(duplicated(v1v2))
print("Unique rows of the data frame:")
print(unique(v1v2))
Output:
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
1 10 10
2 20 30
4 10 20
5 40 0
6 50 50
8 30 30
14. Write a R program to save the information of a data frame in a file and display the
information of the file.
The following steps are used in the R program to create a data frame and save the dataframe
Algorithm:
STEP 1: Create the data frame with name, score, attempts and qualify.
Source code:
exam_data = data.frame(
name = c('Anastasia', 'Dima', 'Katherine', 'James', 'Emily',
'Michael', 'Matthew', 'Laura', 'Kevin', 'Jonas'),
score = c(12.5, 9, 16.5, 12, 9, 20, 14.5, 13.5, 8, 19),
attempts = c(1, 3, 2, 3, 2, 3, 1, 1, 2, 1),
qualify = c('yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no',
'yes')
)
print("Original dataframe:")
print(exam_data)
save(exam_data,file="data.rda")
load("data.rda")
file.info("data.rda")
Output:
To create a matrix taking a given vector of numbers as input. Here we are using a built-in
function matrix() for this conversion. This method helps to creates a matrix from the given
set of values. The syntax of this function is,
byrow: If FALSE (the default) the matrix is filled by columns, otherwise filled by rows.
dimnames: NULL or a list of length 2 giving the row and column names respectively.
The following steps are used in the R program to create a matrix taking a given vector of
numbers as input. In this R program, we directly give the values to built-in functions. And print
the function result. Here we used variables Matx for assigning matrix.
ALGORITHM
STEP 1: Assign variable Matx with matrix values
Output:
[1,] 1 2 3 4
[2,] 5 6 7 8
[3,] 9 10 11 12
16. Write a R program to concatenate two given matrices of same column but different
rows.
The following steps are used in the R program to concatenate two given matrices into a
single matrix. In this R program, we directly give the values to built-in functions. And print the
function result. Here we used two variables namely x and y for assigning matrices. The third
variable fact contains the concatenated matrices and finally prints the resulting matrix.
Algorithm:
STEP 5: Print the concatenated matrices values for same column and different rows
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"
> print(x)
[,1] [,2] [,3]
[1,] 1 5 9
[2,] 2 6 10
[3,] 3 7 11
[4,] 4 8 12
> print("Matrix-2")
[1] "Matrix-2"
> print(y)
[,1] [,2] [,3]
[1,] 13 17 21
[2,] 14 18 22
[3,] 15 19 23
[4,] 16 20 24
> result = dim(rbind(x,y))
> print("After concatenating two given matrices:")
[1] "After concatenating two given matrices:"
> print(result)
[1] 8 3
17. Write a R program to find row and column index of maximum and minimum value
in a given matrix.
The following steps are used in the R program to find the maximum and minimum value in any
given matrix and printing its row and column index.
Algorithm:
STEP 3: Call the built-in function which(m == max(m), arr.ind=TRUE) for row and column
maximum value
STEP 4: Print the Row and column of maximum value of the said matrix
STEP 5: Call the built-in function which(m == min(m), arr.ind=TRUE) for row and column
minimum value
STEP 6: Print the Row and column of minimum value of the said matrix
Source Code:
1] "Original Matrix:"
[,1] [,2] [,3] [,4]
[1,] 1 2 3 4
[2,] 5 6 7 8
[3,] 9 10 11 12
[4,] 13 14 15 16
[1] "Row and column of maximum value of the said matrix:"
row col
[1,] 4 4
[1] "Row and column of minimum value of the said matrix:"
row col
[1,] 1 1
18. Write a R program to append value to a given empty vector
The following steps used in the R program to append values to a given empty vector. In this
R program, we directly give the values to the vector without using the append() function. Here
we are using for loop for the value assigning. The iteration starts from 1 to the length of given
vector values. And the value are assigned like V[i] <- Val[i]. Here we are using V as empty
vector and variable Val as vector values.
ALGORITHM
STEP 1: Consider empty vector as variable V
R Source Code
V= c()
Val = c(9,8,7,6,5,4,3,2,1,0)
for (i in 1:length(Val))
V[i] <- Val[i]
print(V)
Output:
[1] 9,8,7,6,5,4,3,2,1,0
19. Write a R program to multiply two vectors of integers type and length 3
The following 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
Source Code:
[1] 10 30 6
[1] 20 10 40
R program to find the Sum, Mean, and Product of a Vector, ignoring elements like NA or
NaN. Here we are using built-in functions sum, mean, prod for this calculation. The numbers
are passed to these functions directly here. The function sum() returns the sum of all the values
present in its arguments. The sum of the values divided with the number of values in a data series
is calculated using the mean() function. Finally, the prod() is for finding the product of given
arguments.
In the above function argument structure by making na.rm = TRUE we can avoid the elements
like NA, NAN.
The following steps which are used in the R program to find the sum, mean, and product of the
vector values. In this R program, we directly give the values to built-in functions. Consider
variable A for assigning vector value. And call each function by giving A as an argument. Make
sure na.rm should be true as like na.rm = TRUE. Finally, print the function result.
ALGORITHM
Output:
[1] 90
[1] 30
[1] 24000
21. Write a R program to list containing a vector, a matrix and a list and give names to the
elements in the list.
The following steps are used in the R programming to create a vector, matrix and a list.
Given names to the elements to the list.
ALGORITHM
STEP 1: Create a list data that contain vector, matrix and list.
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)
print('1st element:')
print(list_data[1])
print('2nd element:')
print(list_data[2])
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"
The following steps are used in the R programming to create a vector, matrix and a list.
Given names to the elements to the list.
ALGORITHM
STEP 1: Create a list data that contain vector, matrix and list.
Source Code:
[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"
The following steps are used in the R programming to create a vector, matrix and a list.
Given names to the elements to the list.
ALGORITHM
STEP 1: Create a list data that contain vector, matrix and list.
Source Code:
[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"
[[2]]
[[2]][[1]]
[1] "Python"
[[2]][[2]]
[1] "PHP"
[[2]][[3]]
[1] "Java"
24. Write a R program to select second element of a given nested list
In R program to select the second element of a given nested list. Here we are using a built-in
function lapply().
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
the following steps are used in the R program to select the second element of a given nested list.
In this R program, we directly give the values to a built-in function lapply() . Here we are using
the variable values_lst for holding the nested list. And variable rslt_lst is the result list after
applying the function to each element of values_lst. Call the function lapply() for applying the
function FUN to list elements, FUN we used is a double square ' [[ ' which will extract one
element from a list, here we are selecting the second element of each nested list.
ALGORITHM
STEP 3: Call the apply function as lapply(values_lst, '[[', 2) for finding the second element of
each list
Output:
[[1]]
[[1]][[1]]
[1] 1
[[1]][[2]]
[1] 3
[[2]]
[[2]][[1]]
[1] 2
[[2]][[2]]
[1] 5
[[3]]
[[3]][[1]]
[1] 6
[[3]][[2]]
[1] 7
[[1]]
[1] 3
[[2]]
[1] 5
[[3]]
[1] 7
25. Write a R program to merge two given lists into one list.
R program to merge two given lists into one list. Here we are using a built-in combine
function c() for this. The syntax of this function is
The following steps are used in the R program to merge two given lists into one list. In this
R program, we directly give the values to a built-in function c() . Here we are using
variables lst1,lst2 for holding the list elements of two different types. Call the function c() for
merging the two lists and assign them to a list variable merge_lst.
ALGORITHM
STEP 3: Merge the two lists by calling the combine function as c(lst1,lst2)
Source Code:
lst1 = list(5,2,1)
lst2 = list("Red", "Green", "Black")
print("Original lists:")
print(lst1)
print(lst2)
print("Merge the lists:")
merge_lst = c(lst1, lst2)
print("New merged list:")
print(merge_lst)
Output:
[[1]]
[1] 5
[[2]]
[1] 2
[[3]]
[1] 1
[[1]]
[1] "Red"
[[2]]
[1] "Green"
[[3]]
[1] "Black"
[1] "Merge the lists:"
[[1]]
[1] 5
[[2]]
[1] 2
[[3]]
[1] 1
[[4]]
[1] "Red"
[[5]]
[1] "Green"
[[6]]
[1] "Black"
26. Write a R program to create a list named s containing sequence of 15 capital letters,
starting from ‘E’.
The following steps are used in R programming to create a list with named s and print sequence
of letters starting from ‘E’.
Algorithm:
STEP 1: Create a list with named s and starting letter with E and list consist of sequence of 15
letters.
Source Code:
Output:
The following steps are used in the R program to assign new names to the elements of a given
list. In this R program, we directly give the values to a built-in function list(). Here we are using
variables L1 for holding the list elements. Call the function list() with different types of
elements. The function names() helps to get or set the names of an object.
ALGORITHM
STEP 4: Add a new names A,B,C to the element of the list as names(L1) = c("A", "B", "C")
Source Code:
$g1
[1] 1 2 3 4 5
$g2
$g3
[1] "JAVA"
[1] "Assign new names 'A', 'B' and 'C' to the elements of the list"
$A
[1] 1 2 3 4 5
$B
$C
[1] "JAVA"
28. Write a R program to find the levels of factor of a given vector.
In R program to find the levels of a factor of a given vector. Here we are using built-in
functions levels(factor()) for this calculation. The vector values are passed to these functions
directly here. The levels(factor() function in R computes the levels of factors of the vector in a
single function.
The following steps used in the R program to find the levels of a factor of a given vector.
In this R program, we directly give the values to built-in functions. And print the function result.
Here we used variable v for assigning vector values.
ALGORITHM:
OUTPUT
[1] 1 2 3 3 4 NA 3 2 4 5 NA 5
The following steps are used in R programming to create an ordered factor from data consist of
the names of months.
Algorithm:
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:
In R program to concatenate two given factors into a single factor. We can accomplish
the concatenation using built-in functions such as levels() and factor() . In this case, the
The following steps are 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
Source Code
OUTPUT
[1] "Original factors are:"
[1] Q Y M J J H
Levels: H J M Q Y
[1] B J L S F Z
Levels: B F J L S Z
[1] Q Y M J J H B J L S F Z
Levels: B F H J L M Q S Y Z