0% found this document useful (0 votes)
74 views

R Programming Cse I & II

The R program demonstrates creating arrays and matrices. It takes user input of a name and age and displays it. It then prints the R version. It creates vectors, finds unique elements, calculates mean and sum, creates a bar plot of marks, and combines arrays by taking one row from each sequentially. Matrices are created by binding vectors and filling by rows or columns. Arrays are created with a sequence of even integers in a 5x3 format.

Uploaded by

228a1a0558
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)
74 views

R Programming Cse I & II

The R program demonstrates creating arrays and matrices. It takes user input of a name and age and displays it. It then prints the R version. It creates vectors, finds unique elements, calculates mean and sum, creates a bar plot of marks, and combines arrays by taking one row from each sequentially. Matrices are created by binding vectors and filling by rows or columns. Arrays are created with a sequence of even integers in a 5x3 format.

Uploaded by

228a1a0558
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/ 59

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 1: Take user input using readline() into


variables name, age by prompting appropriate messages to the user

STEP 2: print the user input along with other text with the help of paste()

STEP 3: print the current version of R using R.version.string

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:

Input your name: Jhon

Input your age: 23

[1] "My name is Jhon and I am 23 years old."

[1] "R version 4.1.2 (2021-11-01)"


2. Write a R program to get the details of the objects in memory.
STEP 1: Assign variable name,num1,num2, nums with corresponding

values

STEP 2: Call the built-in functions ls() for a listing of objects

STEP 3: First print given objects

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"

[1] "Details of the objects in memory:"

num1 : num 8

num2 : num 1.5

name : chr "Python"

nums : num [1:6] 10 20 30 40 50 60


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.

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

STEP 5: print the result of each function.

Source Code:

print("Sequence of numbers from 20 to 40:")


print(seq(20,40))
print("Mean of numbers from 20 to 60:")
print(mean(20:60))
print("Sum of numbers from 51 to 91:")
print(sum(51:91))

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.

Following is the description of the parameters used −

• marks is a vector or matrix containing numeric values used in bar chart.


• xlab is the label for x axis.
• ylab is the label for y axis.
• main is the title of the bar chart.
• names.arg is a vector of names appearing under each bar.
• col is used to give colors to the bars in the graph.

Source Code:

marks = c(70, 95, 80, 74)


barplot(marks,
main = "Comparing marks of 5 subjects",
xlab = "Marks",
ylab = "Subject",
names.arg = c("English", "Science", "Math.", "Hist."),
col = "darkred",
horiz = FALSE)

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

STEP 2: First print original vector values

STEP 3: Call the function unique as unique(A)

STEP 5: print the result of the function

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:

[1] "Original vector(string)"


[1] "The quick brown fox jumps over the lazy dog."
[1] "Unique elements of the said vector:"
[1] "the quick brown fox jumps over the lazy dog."
[1] "Original vector(number)"
[1] 1 2 2 3 4 4 5 6
[1] "Unique elements of the said vector:"
[1] 1 2 3 4 5 6
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.

ALGORITHM
STEP 1: Assign variables a,b and c with vector values

STEP 2: First print original vector values

STEP 3: combine vectors column-wise by calling cbind(a,b,c)

STEP 4: print the result vector

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:

[1] "Original vectors:"


[1] 1 2 3
[1] 4 5 6
[1] 7 8 9
[1] "Content of the said matrix:"
a b c
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
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.

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,

matrix(data = NA, nrow = 1, ncol = 1, byrow = FALSE,dimnames = NULL)

NA: An optional data vector.

nrow: The desired number of rows.

ncol: The desired number of columns.

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:

m1 = matrix(1:20, nrow=5, ncol=4)


print("5 × 4 matrix:")
print(m1)
cells = c(1,3,5,7,8,9,11,12,14)
rnames = c("Row1", "Row2", "Row3")
cnames = c("Col1", "Col2", "Col3")
m2 = matrix(cells, nrow=3, ncol=3, byrow=TRUE, dimnames=list(rnames,
cnames))
print("3 × 3 matrix with labels, filled by rows: ")
print(m2)
print("3 × 3 matrix with labels, filled by columns: ")
m3 = matrix(cells, nrow=3, ncol=3, byrow=FALSE, dimnames=list(rnames,
cnames))
print(m3)

Output:

[1] "5 × 4 matrix:"


[,1] [,2] [,3] [,4]
[1,] 1 6 11 16
[2,] 2 7 12 17
[3,] 3 8 13 18
[4,] 4 9 14 19
[5,] 5 10 15 20
[1] "3 × 3 matrix with labels, filled by rows: "
Col1 Col2 Col3
Row1 1 3 5
Row2 7 8 9
Row3 11 12 14
[1] "3 × 3 matrix with labels, filled by columns: "
Col1 Col2 Col3
Row1 1 7 11
Row2 3 8 12
Row3 5 9 14
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.
The arrays vectors can be created in R using the rbind() operation, by binding the rows
together. The row binding operation in R creates a matrix that contains the number of rows
specified. Similarly, n number of arrays can be created. The cbind() operation is then applied
which takes as arguments the array vectors. It creates a combined matrix where the merging
takes place using columns.
cbind(arr1, arr2, arr3..)

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

Syntax: matrix ( data, ncol, byrow)


Arguments :
• data – The data to convert into a matrix
• ncol – The number of columns to produce in the result matrix
• byrow – logical. If FALSE (the default) the matrix is filled by columns, otherwise
the matrix is filled by rows.

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:

STEP 1: Assign array elements into the variable Arr

STEP 2: The sequence of elements are created by using seq()

STEP 3:limit the count to 15 as length.out = 15 and the numbers should be


even, difference between the numbers is 2 as by=2

STEP 4: Print the 5x3 array

Source Code:

a <- array(seq(from = 50, length.out = 15, by = 2), c(5, 3))


print("Content of the array:")
print("5×3 array of sequence of even integers greater than 50:")
print(a)

Output:

[1] "Content of the array:"


[1] "5×3 array of sequence of even integers greater
than 50:"
[,1] [,2] [,3]
[1,] 50 60 70
[2,] 52 62 72
[3,] 54 64 74
[4,] 56 66 76
[5,] 58 68 78
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.

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)

arra1 = array(c(v1, v2),dim = c(3,4,2))

print(arra1)

Output:

, , 1

[,1] [,2] [,3] [,4]


[1,] 1 7 4 10
[2,] 3 4 6 1
[3,] 5 2 8 3

, , 2

[,1] [,2] [,3] [,4]


[1,] 5 2 8 3
[2,] 7 4 10 5
[3,] 4 6 1 7
11. Write a R program to create an empty data frame.

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

STEP 1: Consider variable Df as a data frame.

STEP 2: Call data.frame() with different data types

STEP 3: Assign Df with function result

STEP 4: print the result of the function

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:"

'data.frame': 0 obs. of 5 variables:

$ Ints : int

$ Doubles : num

$ Characters: chr

$ Logicals : logi

$ Factors : Factor w/ 0 levels:

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

function data.frame() for creating a data frame in R. The

function data.frame() creates data frames that have tightly coupled

collections of variables.

The syntax of this function is:

data.frame(…, row.names = NULL, check.rows = FALSE,check.names = TRUE,

fix.empty.names = TRUE,stringsAsFactors = default.stringsAsFactors())

Where dots(...) indicates the arguments are of either the form value or tag =

value and row.names is a NULL or a single integer or character string.

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

holding different types of vectors. Call the function data.frame() for

creating a data frame.


ALGORITHM

STEP 1: Assign variables contestant,points,tries,win with vector values

STEP 2: First print original vector values

STEP 3: Call the in-built

function data.frame(contestant,points,tries,win) and assign the result of

the function to variable df

STEP 4: print the data frame df

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] "John" "Michael" "Albert" "James" "Kevin"

[1] 10.0 9.2 14.0 12.5 18.0

[1] 1 3 2 3 2

[1] "yes" "no" "yes" "no" "no"

contestant points tries win

1 John 10.0 1 yes

2 Michael 9.2 3 no

3 Albert 14.0 2 yes

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.

The syntax of this function is:

data.frame(…, row.names = NULL, check.rows = FALSE,check.names = TRUE,


fix.empty.names = TRUE,stringsAsFactors = default.stringsAsFactors())

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

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)


Source Code:

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:

[1] "Original data frame:"

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] "Duplicate elements of the data frame:"

[1] FALSE FALSE TRUE FALSE FALSE FALSE TRUE FALSE

[1] "Unique rows of the data frame:"


a b

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

and display the information of the file.

Algorithm:

STEP 1: Create the data frame with name, score, attempts and qualify.

STEP 2: First print original dataframe

STEP 3: Save the dataframe

STEP 4: load dataframe and display file info.

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:

> 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:")
[1] "Original dataframe:"
> print(exam_data)
name score attempts qualify
1 Anastasia 12.5 1 yes
2 Dima 9.0 3 no
3 Katherine 16.5 2 yes
4 James 12.0 3 no
5 Emily 9.0 2 no
6 Michael 20.0 3 yes
7 Matthew 14.5 1 yes
8 Laura 13.5 1 no
9 Kevin 8.0 2 no
10 Jonas 19.0 1 yes
> save(exam_data,file="data.rda")
> load("data.rda")
> file.info("data.rda")
size isdir mode mtime ctime
data.rda 344 FALSE 644 2022-06-16 08:19:49 2022-06-
16 08:19:49
atime uid gid uname grname
data.rda 2022-06-16 08:19:49 1000 1000 trinket
trinket
15. Write a R program to create a matrix from a list of given vectors.

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,

matrix(data = NA, nrow = 1, ncol = 1, byrow = FALSE,dimnames = NULL)

NA: An optional data vector.

nrow: The desired number of rows.

ncol: The desired number of columns.

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

STEP 2: Create a matrix of 12 elements with 3 rows

STEP 3: Create by calling like matrix(c(1:12), nrow = 3, byrow = TRUE)

STEP 4: print the result matrix


Source Code:

Matx = matrix(c(1:12), nrow = 3, byrow = TRUE)


print("Original Matrix is:")
print(Matx)

Output:

[1] "Original Matrix is:"

[,1] [,2] [,3] [,4]

[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 1: Assign variable x and y with values

STEP 2: First print original matrices values

STEP 3: Call the built-in function factor with level as dim(rbind(x,y))

STEP 4: Assign variable result with the function result

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 1: Create a matrix with 4 rows and 4 columns

STEP 2: First print original matrices values

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:

m = matrix(c(1:16), nrow = 4, byrow = TRUE)


print("Original Matrix:")
print(m)
result = which(m == max(m), arr.ind=TRUE)
print("Row and column of maximum value of the said matrix:")
print(result)
result = which(m == min(m), arr.ind=TRUE)
print("Row and column of minimum value of the said matrix:")
print(result)
Output:

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

STEP 2: Consider vector values as variable Val

STEP 3: Iterate through for loop from 1 to length(Val)

STEP 4: Assign values to empty vector as V[i] <- Val[i]

STEP 4: Print the vector V as result

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

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:

A = c(10, 20, 30)


B = c(20, 10, 40)
print("Original Vectors are:")
print(A)
print(B)
print("Product of two Vectors:")
C = A * B
print(C)
Output:

[1] "Original Vectors:"

[1] 10 30 6

[1] 20 10 40

[1] "Product of two Vectors:"

[1] 200 300 240


20.Write a R program to find Sum, Mean and Product of a Vector, ignore element like
NA or NaN

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.

sum(…, na.rm = FALSE)


mean(x, …)
prod(…, na.rm = FALSE)

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

STEP 1: Use the built-in functions

STEP 2: call sum() with vector and na.rm = TRUE as argument

STEP 3: call mean() with vector and na.rm = TRUE as argument

STEP 4: call prod() with vector and na.rm = TRUE as argument

STEP 5: print the result of each function


Source Code
A = c(30, NULL, 40, 20, NA)
print("Sum is:")
#ignore NA and NaN values
print(sum(A, na.rm=TRUE))
print("Mean is:")
print(mean(A, na.rm=TRUE))
print("Product is:")
print(prod(A, na.rm=TRUE))

Output:

[1] "Sum is:"

[1] 90

[1] "Mean is:"

[1] 30

[1] "Product is:"

[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.

STEP 2: Assign the names to the list data.

STEP 3 : Print the data with column names which as given.

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"

[1] "List with column names:"


$Color
[1] "Red" "Green" "Black"

$`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"

[1] "1st element:"


$Color
[1] "Red" "Green" "Black"

[1] "2nd element:"


$`Odd numbers`
[,1] [,2] [,3]
[1,] 1 5 9
[2,] 3 7 11
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.

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.

STEP 2: Assign the names to the list data.

STEP 3 : Print the data with column names which as given.

STEP 4: Access the first and second element of the 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"

[1] "List with column names:"


$Color
[1] "Red" "Green" "Black"

$`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"

[1] "1st element:"


$Color
[1] "Red" "Green" "Black"

[1] "2nd element:"


$`Odd numbers`
[,1] [,2] [,3]
[1,] 1 5 9
[2,] 3 7 11
23. Write a R program to create a list containing a vector, a matrix and a list and remove the
second element.

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.

STEP 2: Assign the names to the list data.

STEP 3 : Print the list data

STEP 4: Remove the second element of the list

STEP 5: Print the list data after removing.

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)
print("Remove the second element of the list:")
list_data[2] = NULL
print("New list:")
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"

[1] "Remove the second element of the list:"


[1] "New list:"
[[1]]
[1] "Red" "Green" "Black"

[[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().

he syntax of this function is

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 1: Assign variable values_lst with a nested list

STEP 2: Print the original nested list

STEP 3: Call the apply function as lapply(values_lst, '[[', 2) for finding the second element of

each list

STEP 4: Assign result list into the variable rslt_lst

STEP 4: Print the result


Source code:

values_lst = list(list(1,3), list(2,5), list(6,7))


print("Original nested list is:")
print(values_lst)
rslt_lst = lapply(values_lst, '[[', 2)
print("Second element of the nested list is:")
print(rslt_lst)

Output:

[1] "Original nested list is:"

[[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] "Second element of the nested list is:"

[[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

c(…) # Where ... indicates object to be concatenate

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 1: Assign variables lst1,lst2 with a list of two different types

STEP 2: Print the original lists

STEP 3: Merge the two lists by calling the combine function as c(lst1,lst2)

STEP 4: Assign merged lists into the variable merge_lst

STEP 5: Print the merged list merge_lst

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] "Original lists:"

[[1]]

[1] 5

[[2]]

[1] 2

[[3]]

[1] 1

[[1]]

[1] "Red"

[[2]]

[1] "Green"

[[3]]

[1] "Black"
[1] "Merge the lists:"

[1] "New merged list:"

[[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.

STEP 2: Print the list.

Source Code:

s = LETTERS[match("E", LETTERS):(match("E", LETTERS)+15)]


print("Content of the list:")
print("Sequence of 15 capital letters, starting from ‘E’-")
print(s)

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"
27. Write a R program to assign new names "a", "b" and "c" to the elements of a given
list.

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 1: Assign variables L1 with a list

STEP 2: Create L1 with 3 sets of elements g1,g2,g3

STEP 3: Print the original lists

STEP 4: Add a new names A,B,C to the element of the list as names(L1) = c("A", "B", "C")

STEP 5: Print the final list L1

Source Code:

L1 = list(g1 = 1:5, g2 = "C Programming", g3 = "JAVA")


print("Original list:")
print(L1)
names(L1) = c("A", "B", "C")
print("Assign new names 'A', 'B' and 'C' to the elements of the list")
print(L1)
Output:

[1] "Original list:"

$g1

[1] 1 2 3 4 5

$g2

[1] "C Programming"

$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

[1] "C Programming"

$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:

STEP 1: Assign variable v with vector values

STEP 2: Use the built-in functions

STEP 3: First print original vector values

STEP 4: levels(factor(v) with an argument as v to find levels of factors

STEP 5: print the result of the function


Source Code

v = c(1, 2, 3, 3, 4, NA, 3, 2, 4, 5, NA, 5)


print("The original vector is:")
print(v)
print("Levels of factor of the vector:")
print(levels(factor(v)))

OUTPUT

[1] "The original vector is:"

[1] 1 2 3 3 4 NA 3 2 4 5 NA 5

[1] "Levels of factor of the vector:"

[1] "1" "2" "3" "4" "5"


29. Write a R program to create an ordered factor from data consisting of the names of
months.

The following steps are used in R programming to create an ordered factor from data consist of
the names of months.

Algorithm:

STEP 1: Create an vector , that consist of names of month

STEP 2: Print the original vector

STEP 3: Print the ordered factor of the given vector.

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
30. Write a R program to concatenate two given factor in a single factor

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

vector values are passed directly to these functions.

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

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

fact1 <- factor(sample(LETTERS, size=6, replace=TRUE))


fact2 <- factor(sample(LETTERS, size=6, replace=TRUE))
print("Original factors are:")
print(fact1)
print(fact2)
fact= factor(c(levels(fact1)[fact1], levels(fact2)[fact2]))
print("After concatenate factor becomes:")
print(fact)

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] "After concatenate factor becomes:"

[1] Q Y M J J H B J L S F Z

Levels: B F H J L M Q S Y Z

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy