R Lab Programs
R Lab Programs
WEEK-1
2)NUMERIC :
.b=3.4
paste(.b)
class(.b)
3)COMPLEX :
.c=complex(real=2,imaginary=3)
paste("The complex number is:",.c)
class(.c)
print(is.complex(.c))
4)LOGICAL :
.d=2**3
print(.d)
v <- c(33,10,TRUE,1+5i)
t <- c(41,14,FALSE,1+4i)
print(v&t)
v <- c(73,0,TRUE,52+2i)
t <- c(49,0,FALSE,92+3i)
print(v|t)
Takes the first element of both the vectors and gives the TRUE only if both are
TRUE.
v <- c(3,0,TRUE,1+5i)
t <- c(1,3,TRUE,1+4i)
print(v&&t)
Takes the first element of both the vectors and gives the TRUE if one of them is
TRUE.
v <- c(0,0,TRUE,1+5i)
t <- c(0,3,TRUE,1+4i)
print(v||t)
5)CHARACTER :
a='HAI R Programming'
print(a)
-------------------------------------------------------------------------------------
Write a program to print inbuilt value of PI:
print(pi)
print(letters)
print(LETTERS)
print(month.abb)
print(month.name)
-------------------------------------------------------------------------------------
Write a program to convert other type of variables into complex type:
a=5.2
print(as.complex(a))
b=3
print(as.complex(b))
c=2&&3
print(as.complex(c))
-------------------------------------------------------------------------------------
write a program to convert numeric into character type:
a=3.5
print(as.character(a))
-------------------------------------------------------------------------------------
Write a program to concatenate "R" and "Programming":
a="R"
b="Programming"
paste(a,b) #This will return an object.
cat("R","Programming") #This will nor return an object just to display.
-------------------------------------------------------------------------------------
Write a program to check whether the entered number is 0 or 1 0 or anyother
using function:
Zero<-function(a)
{
if(a==0)
{
return("The entered number is 0")
}
else if(a==1)
{
return("The entered number is 1")
}
else
{
return("The entered number is other than 0 and 1")
}
}
a=readline()
Zero(a)
--------------------------------------------------------------------------------------
Perform addition using default concept using function:
Sum<-function(a=1,b=2)
{
return(a+b)
}
print(Sum())
-------------------------------------------------------------------------------------------
Print Factorial of a given number using recursive and Non-recursive function:
NonRecFact<-function(a)
{
if(a==0 || a==1)
{
return(1)
}
else
{
f=1
for(i in 2:a)
{
f=f*i
}
return(f)
}
}
a=readline()
print(NonRecFact(a))
rec_fac<-function(x){
if((as.numeric(x))<=1)
{
return(1)
}
else
{
return(as.numeric(x)*rec_fac(as.numeric(x)-1))
}
}
a=readline()
paste(rec_fac(a))
-------------------------------------------------------------------------------------
Write a program to check whether the given number is prime or not:
n=as.integer(readline(prompt="Enter a number: "))
c=0
for(i in 1:n)
{
if((n%%i)==0)
{
c=c+1
}
}
if(c==2)
{
print(paste(n,"is a prime number"))
}else
{
print(paste(n,"is not a prime number"))
}
------------------------------------------------------------------------------------
perform all Arithmetic operations:
print(2+3)
print(3-2)
print(2*3)
print(3/2)
print(4**3)
print(9%%10)
-----------------------------------------------------------------------------------
Create a function to print squares of numbers in sequence:
Square<-function(a)
{
return(a*a)
}
n=as.numeric(readline(prompt="Enter number:"))
for(i in 1:n)
{
print(Square(i))
}
------------------------------------------------------------------------------------
print even numbers using for loop
for(i in 1:100)
{
if(i%%2==0)
{
print(i)
}
}
print even numbers using while loop
i=1
while(i<101)
{
if(i%%2==0)
{
print(i)
}
i=i+1
}
print even numbers using repeat loop
a=1
repeat
{
if(a%%2==0){print(a)}
a=a+1
if(a==101){break}
}
----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------
WEEK-2
1)WRITE A PROGRAM TO CREATE VECTORS OF 5
ELEMENTS OF INTEGER DATA TYPE AND DISPLAY.
a=c(1:5)
print(a)
-------------------------------------------------------------------------------------
2)TO DISPLAY TYPEOF() GIVEN VECTOR ELEMENTS.
a=c(1:5)
print(typeof(a))
-------------------------------------------------------------------------------------
3)TO CALCULATE TOTAL ELEMENTS IN A GIVEN VECTOR.
a=c(1:10)
print(length(a))
-------------------------------------------------------------------------------------
4)TO DISPLAY VECTOR ELEMENTS.
a=c(1:6)
b=c(1,2,TRUE,4)
d=seq(1,10,2)
e=c(5,6,FALSE,2+3i)
print(a)
print(b)
print(d)
print(e)
-------------------------------------------------------------------------------------
5)To delete the 4th and 5th elements from a vector of 10
elements.
a=c(1:10)
print(a)
b=a[!a %in% c(4,5)]
print(b)
-------------------------------------------------------------------------------------
6)To retrieve the values from a vector which has a value greater
than 20.
a=c(1,23,14,25,9,6,24)
b=a[a>20]
print(b)
-------------------------------------------------------------------------------------
7)WRITE A PROGRAM TO ADD TWO VECTORS AND
SUBTRACT TWO VECTORS.
a=c(1,2,3,4,5)
b=c(15,17,20,33,54)
print(a+b)
print(a-b)
print(b-a)
print(a*b)
-------------------------------------------------------------------------------------
**8)TO CREATE A TABLE NAMED PROGRAMMING
LANGUAGES CONTAINING COLUMN NAMES:
programming language name;semester;marks;attendance.
paste("PROGRAMMING LANGUAGES")
college=data.frame(programming_language_name=c('C','JAVA','P
YTHON','R'),semester=c('I','III','IV','V'),marks=c(90,89,91,95),atten
dance=c(100,100,100,100))
print(college)
-------------------------------------------------------------------------------------
9)To extract only percentages from the data frame.
college=data.frame(programming_language_name=c('C','JAVA','P
YTHON','R'),semester=c('I','III','IV','V'),marks=c(90,89,91,95),atten
dance=c(100,100,100,100))
str(college)
num_cols=unlist(lapply(college,is.numeric))
print(college[,num_cols])
-------------------------------------------------------------------------------------
10)To create a list with vectors.
a=list(c(1,2,3),c(TRUE,FALSE,TRUE),c("R"))
a
-------------------------------------------------------------------------------------
11)To create a list without Vectors.
a=list(1,2,2.5,2+3i,TRUE,"R LAB")
a
-------------------------------------------------------------------------------------
12)To create a list with naming Fields:
x=list("a"=c(1,2,3),"b"=c(TRUE,FALSE),"k"=c("R","C"))
print(x)
x$a
-------------------------------------------------------------------------------------
13)To access lists using naming fields:
x=list("a"=c(1,2,3),"b"=c(TRUE,FALSE),"k"=c("R","C"))
x[["b"]]=FALSE
x[["f"]]=c(1+2i,3+4i)
x[["b"]]=NULL # eliminates b field in the list
print(x)
print(length(x))
-------------------------------------------------------------------------------------
14)rbind() function is used to combine specified
vector,matrix,dataframe by rows:
x=2:7
y=c(10:15)
rbind(x,y) # the number of columns of the result must be multiple
of vector length.
x=1:5
rbind(x,4) # by default deparse.level=1
rbind(x,5,deparse.level=0)
rbind(x,6,deparse.level=2)
-------------------------------------------------------------------------------------
15)cbind() function is used to combine vIa columns.
x=2:7
y=c(10:15)
cbind(x,y)
x=1:5
cbind(x,4) # by default deparse.level=1
cbind(x,5,deparse.level=0)
cbind(x,6,deparse.level=2)
-------------------------------------------------------------------------------------
STRING FUNCTIONS
1)nchar():
syntax: nchar(x,type="char",allowNA=FALSE,keepNA=NA)
x is a character vector
type is type of data stored inside a vector
-------------------------------------------------------------------------------------
2)toupper() function turns the characters into uppercase.
a="Hello Welcome To R Lab"
toupper(a)
b=c("hi","hey","hello")
toupper(b)
-------------------------------------------------------------------------------------
3)tolower() function turns the characters into lowercase.
b=c("HI","HEY","HELLO")
tolower(b)
-------------------------------------------------------------------------------------
4)substr() function:
syntax: substr(x,start,stop)
a="Hello Welcome To R Lab"
substr(a,5,18)
-------------------------------------------------------------------------------------
5)grep() function searches for a pattern inside a given string and
returns the number of instances a match is found.
a="Hello Welcome To R lablab a good and practise lab"
grep("lab",a)
grep("abc",a)
-------------------------------------------------------------------------------------
6)sprintf():
sprintf("%s scored %.2f percent","geethu",98.5)
-------------------------------------------------------------------------------------
7)strsplit():
s="Splitting sentence into words"
strsplit(s," ")
a="I:am:good:girl"
strsplit(a,":")
-------------------------------------------------------------------------------------
8)paste(str,sep=" ",collapse=NULL)
paste("Hi","hello","Good Morning",sep="--")
str=paste(c(1:3),"4",sep=":")
print(str)
-------------------------------------------------------------------------------------
9)cat(str,file=" ",sep=" ",append="FALSE")
cat("hello","this","is","geethika\n")
cat("hello","this","is","geethika",sep=" @ ")
-------------------------------------------------------------------------------------
10)sub() function replaces the first occurence of a substring in
string with another substring.
syntax: sub(old,new,string)
s="Splitting sentence into words"
sub("sentence","SENTENCE",s)
-------------------------------------------------------------------------------------
11)length() function determines number of strings specified in the
function.
print(length(c("Lead","A","GOOD","LIFE")))
-------------------------------------------------------------------------------------
12)casefold() function by default converts into lower case
syntax: casefold(str,upper=TRUE)
print(casefold(c("hai this is geethika"),upper=TRUE))
-------------------------------------------------------------------------------------
13)chartr() characters translation:
syntax: chartr(old char,newchar,string)
chartr("a","A","An honest man gave that food.")
chartr("is","#@",c("This is it","It is great"))
-------------------------------------------------------------------------------------
14)abbreviate():
streets=c("Main","Elm","Riverbend","Mario","Frederick")
abbreviate(streets)
abbreviate(streets,minlength=2)
###abbreviate(state.name)and abbreviate(state.abb) are inbuilt
functions
-------------------------------------------------------------------------------------
15)unlist()
a="All-Alas-Arizo-Califor"
unlist(strsplit(a,split="-"))
----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------
LAB PROGRAMS FOR END SEMESTER
BASICS:
Write an R program to take input from the user (name and age)
and display the values and also print the version of R installation
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)
-------------------------------------------------------------------------------------
Write an R program to get all prime numbers up to a given
number
prime_numbers <- function(n) {
if (n >= 2) {
x = seq(2, n)
prime_nums = c()
for (i in seq(2, n)) {
if (any(x == i)) {
prime_nums = c(prime_nums, i)
x = c(x[(x %% i) != 0], i)
}
}
return(prime_nums)
}
else
{
stop("Input number should be at least 2.")
}
}
prime_numbers(12)
-------------------------------------------------------------------------------------
Write an R program to get the first 10 Fibonacci numbers.
Fibonacci <- numeric(10)
Fibonacci[1] <- Fibonacci[2] <- 1
for (i in 3:10) Fibonacci[i] <- Fibonacci[i - 2] + Fibonacci[i - 1]
print("First 10 Fibonacci numbers:")
print(Fibonacci)
-------------------------------------------------------------------------------------
Write an 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.
print("Sequence of numbers from 20 to 50:")
print(seq(20,50))
print("Mean of numbers from 20 to 60:")
print(mean(20:60))
print("Sum of numbers from 51 to 91:")
print(sum(51:91))
-------------------------------------------------------------------------------------
Write an R program to convert other types of objects into complex
type objects.
a=5.2
print(as.complex(a))
b=3
print(as.complex(b))
c=2&&3
print(as.complex(c))
-------------------------------------------------------------------------------------
Write an R program to print the numbers from 1 to 100 and print
"AAA" for multiples of 3, print "BBBBB" for multiples of 5, and print
"AAABBB" for multiples of both.
for (n in 1:100) {
if (n %% 3 == 0 & n %% 5 == 0) {print("AAABBBBB")}
else if (n %% 3 == 0) {print("AAA")}
else if (n %% 5 == 0) {print("BBBBB")}
else print(n)
}
-------------------------------------------------------------------------------------
Write an R program to extract the first 10 english letters in
lowercase and last 10 letters in upper case and extract letters
between 22nd to 24th letters in uppercase.
print("First 10 letters in lowercase:")
t = head(letters, 10)
print(t)
print("Last 10 letters in upper case:")
t = tail(LETTERS, 10)
print(t)
print("Letters between 22nd to 24th letters in uppercase:")
e = tail(LETTERS[22:24])
print(e)
-------------------------------------------------------------------------------------
Write an R program to find a list of even numbers from 1 to n.
for (num in 1:10) {
if (num %% 2 == 0) {
print(paste("Even number is :", num))
}
}
-------------------------------------------------------------------------------------
Write an R program to create a function to print squares of a
number in sequence
new.function <- function() {
for(i in 1:5) {
print(i^2)
}
}
new.function()
-------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
DATA TYPES:
-------------------------------------------------------------------------------------
Write an R program to create a 5 × 4 matrix, 3 × 3 matrix with
labels and fill the matrix by rows and 2 × 2 matrix with labels and
fill the matrix by columns.
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)
-------------------------------------------------------------------------------------
Write an R program to sort a Vector in ascending and descending
order.
x = c(60, 10, 50, 20, 40, 30)
print("Original Vectors:")
print(x)
print("Sort in ascending order:")
print(sort(x))
print("Sort in descending order:")
print(sort(x, decreasing=TRUE))
-------------------------------------------------------------------------------------
Write an R program to find the maximum and the minimum value
of a given vector
nums = c(10, 20, 30, 40, 50, 60)
print('Original vector:')
print(nums)
print(paste("Maximum value of the given vector:",max(nums)))
print(paste("Minimum value of the given vector:",min(nums)))
-------------------------------------------------------------------------------------
Write an R program to create a list of heterogeneous data, which
include character, numeric and logical vectors. Print the lists.
my_list = list(Chr="R PROGRAMMING", nums = 1:15,
flag=TRUE)
print(my_list)
-------------------------------------------------------------------------------------
Write an R program to create a Data frame which contain details
of 5 employees and display the details
Employees = data.frame(Name=c("RAJ","RAM","RAHUL",
"RIYA","RAMESH"),
Gender=c("M","M","M","F","M"),
Age=c(23,22,25,20,32),
Designation=c("Clerk","Manager","Executive","CEO","ASSISTAN
T"),
SSN=c("123-34-2346","123-44-779","556-24-433","123-98-987","
679-77-576")
)
print("Details of the employees:")
print(Employees)
-------------------------------------------------------------------------------------
Write an 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 the first row of the third array.
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)
-------------------------------------------------------------------------------------
Write an R program to create an array of two 3x3 matrices each
with 3 rows and 3 columns from two given two vectors. Print the
second row of the second matrix of the array and the element in
the 3rd row and 3rd column of the 1st matrix.
print("Two vectors of different lengths:")
v1 = c(1,3,4,5)
v2 = c(10,11,12,13,14,15)
print(v1)
print(v2)
result = array(c(v1,v2),dim = c(3,3,2))
print("New array:")
print(result)
print("The second row of the second matrix of the array:")
print(result[2,,2])
print("The element in the 3rd row and 3rd column of the 1st
matrix:")
print(result[3,3,1])
------------------------------------------------------------------------------------
Write an R program to create a Data frame which contain details
of 5 employees and display summary of the data
Employees = data.frame(Name=c("RIYA","RAM","RAHUL",
"RIYA","RAMESH"),
Gender=c("F","M","M","F","M"),
Age=c(20,22,25,20,32),
Designation=c("CEO","Manager","Executive","CEO","ASSISTANT
"),
SSN=c("123-34-2346","123-44-779","556-24-433","123-98-987","
679-77-576")
)
print("Summary of the data:")
print(summary(Employees))
-------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
Strings:
1)Write a R program to check whether the given string is
palindrome or not
r=readline("Enter string to check palindrome : ")
rev=""
for (i in nchar(r):1)
{
rev=paste(rev,substr(r,i,i),sep = "")
}
if (rev==r){
print("TRUE")
}else{
print("FALSE")
}
-------------------------------------------------------------------------------------
2)Write a program to convert the string into lowercase and
uppercase letters
s="RlAbPrOgRam"
print(paste("string : ",s))
print(paste("lowercase : ",tolower(s)))
print(paste("Uppercase : ",toupper(s)))
-------------------------------------------------------------------------------------
3)Write a program to extract characters from 5th to 7th position
from a given string
s="RlAbPrOgRam"
print(paste("string : ",s))
print("Extract string from 5 to 7")
print(substr(s,5,7))
-------------------------------------------------------------------------------------
Write an R program to find duplicate characters from a given string.
k=readline("Enter string : ")
print("Duplicates")
for (i in 1:nchar(k))
{
for (j in i+1:nchar(k))
{
if (substr(k,i,i)==substr(k,j,j))
{
print(substr(k,i,i))
}
}
}
-------------------------------------------------------------------------------------
Write an R program to extract substring from a given main string.
print("Finding substring")
str1="Welcome to r programming"
print(substr(str1,4,12))
-------------------------------------------------------------------------------------
Write an R program to describe any five string handling functions.
print("string handling funtions")
a="R LAB"
print("num of characters")
print(nchar(a))
a1="r prog LAB"
print("Upper case letters")
print(toupper(a1))
print("Lower case letters")
print(tolower(a))
s1="R programming lab"
print("Sunstring")
print(substr(s1,3,13))
s2="split statement into words"
print("Splitting string")
print(strsplit(s2," "))
print("Using paste")
str=paste("hi","welcome","to","r",sep=" ")
print(str)
-------------------------------------------------------------------------------------
Write an R program to check whether the substring is present in main
string or not
r1="r prog lab"
r2="prog"
print("Check whether string is substring or not ")
print(grepl(r2,r1,fixed = TRUE))
-------------------------------------------------------------------------------------
Write an R program to count duplicate characters from a given string.
c=0
k=readline("Enter string : ")
print("Count of duplicates")
for (i in 1:nchar(k))
{
for (j in i+1:nchar(k))
{
if (substr(k,i,i)==substr(k,j,j))
{
c=c+1
}
}
}
print(c)
---------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------
STATISTICS:
Write an R program to create a simple bar plot of three subject’s marks,
change the border color to brown and make inside bar lines as 90
degrees.
barplot(c(80,90,95),main="Marks of
subjects",names.arg=c('phy','chem','math'),xlab='subjects',ylab='marks',b
order='brown',density=10,angle=90)
---------------------------------------------------------------------------------------
Write a program to read a csv file and analyze the data in the file in R.
---------------------------------------------------------------------------------------
Write an R program to draw an empty pie chart and empty plots specify
the axes limits of the graph
---------------------------------------------------------------------------------------
Write an R program to create a simple bar plot of four subject’s
registered, assign the colors to each bar and assign the limit to x-axis as
c(0,5) and y-axis as c(0,50).
H<-c(12,22,30,45)
barplot(H,main="Marks
details",xlim=c(0,5),ylim=c(0,50),xlab='subjects',ylab='marks',col=rainb
ow(length(H)),names.arg=c('phy','che','math','eng'))
---------------------------------------------------------------------------------------
Write an R program to create a simple 3D pie chart, assign color and
labels to each part.
library(plotrix)
x<- c(21,62,10,53)
lbl<- c("LONDON","NEW YORK","SINGAPORE","MUMBAI")
pie3D(x,labels = lbl, main = "pie chart of countries")
---------------------------------------------------------------------------------------
Write an R program to create a simple bar plot of five subject’s marks.
barplot(c(80,90,95,81,67),main="Marks of
subjects",names.arg=c('phy','chem','math','eng','tel'),xlab='subjects',ylab=
'marks')
---------------------------------------------------------------------------------------
Write an R program to create a simple pie chart of four subjects
registered, assign the colors to each block and display in anti-clockwise
direction.
A<-c(20,33,58,89)
pie(A,labels=c('phy','chem','eng','math'),col=rainbow(length(A)),main='
Marks List',clockwise=FALSE)
---------------------------------------------------------------------------------------
Write an R program to create a simple 3D pie chart, assign title to the
chart and also split each part.
library(plotrix)
x<- c(21,62,10,53)
lbl<- c("LONDON","NEW YORK","SINGAPORE","MUMBAI")
pie3D(x,labels = lbl,explode = 0.1, main = "pie chart of countries")
---------------------------------------------------------------------------------------
Write an R program to draw an empty bar plot and empty plots specify
the axes limits of the graph.
plot.new()
plot(-1,xlab="", ylab="", xlim=c(0, 20), ylim=c(0, 20))
---------------------------------------------------------------------------------------
Write an R program to create a simple pie chart of three subject’s marks,
change the border color to pink and make inside bar lines as 60 degrees.
A<-c(20,33,58,89)
pie(A,labels=c('phy','chem','eng','math'),col=rainbow(length(A)),main='
Marks List',border='pink',density=10,angle=60)
---------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------