0% found this document useful (0 votes)
34 views25 pages

R Manual - Merged

Uploaded by

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

R Manual - Merged

Uploaded by

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

Exercise-1

AIM:

a) Installing R and RStudio

b) Basic functionality of R.variable,data types in R

a)

1. Installing R and RStudio

To use R, you first need to install the R program on your computer.

Install R on windows

To install R on your Windows computer, follow these steps:

1. Go to http://cran.r-project.org/

2. Under “Download and Install R”, click on the “Download for Windows” link.

3. Step – 3: Click on the base subdirectory link or install R for the first time link.

4. Step – 4: Click Download R X.X.X for Windows (X.X.X stand for the latest version of R. eg:

3.6.1) and save the executable .exe file.

5. Step – 5: Run the .exe file and follow the installation instructions.

5.a. Select the desired language and then click Next

5.b. Read the license agreement and click Next

5.c. Select the components you wish to install (it is recommended to install all the

components). Click Next.

5.d. Enter/browse the folder/path you wish to install R into and then confirm by clicking Next.

5.e Wait for the installation process to complete


Installation of Rstudio

Step – 1: With R-base installed, for installing RStudio. go to download RStudio and click on the

download button for RStudio desktop.

Step – 2: Click on the link for the windows version of RStudio and save the .exe file.

Step – 3: Run the .exe and follow the installation instructions.

3.a. Click Next on the welcome window.

3.b. Enter/browse the path to the installation folder and click Next to proceed.

3.c. Select the folder for the start menu shortcut or click on do not create shortcuts and
then click Next.

3.d. Wait for the installation process to complete.

3.e. Click Finish to end the installation

Basic functionality of R, variable, data types in R

RStudio Interface

RStudio is split into 4 quadrants:

 Script (top left): where commands are written, executed, and saved
 Environment (top right): lists the data, variables, and functions that are currently in
the workspace
 Console (bottom left): for quickly testing code and where commands and outputs are
displayed, except plots
 Plot (bottom right): where graphics are displayed

How to start an R project


 Start RStudio
 Under the File menu, click on
 New project, choose New directory, then Click Empty project
 As directory (or folder) name enter r-intro and create project as subdirectory of your
desktop folder: ~/Desktop
 Click on Create project
• Using R Scripts
• To create new script in R in Console
• Commands can be run directly from the console, but creating an R Script allows you
to edit and reuse previous commands and to create more complicated lists of commands.A
script also allows you to save your commands to be reopened later.

You create new R Script by clicking on File > New File > R Script in the RStudio menu bar.

 To execute your code in the R script, you can either highlight the code and click on Run,
or you can highlight the code and press CTRL + Enter on your keyboard.
 If you prefer, you can enter code directly in the Console Window and click Enter. The
commands that you run will be shown in the History Window on the top right of RStudio.
You can save these commands for future use.

R Script file is a file with extension “.R” that contains a program (a set of commands). Rscript
is an R Interpreter which helps in the execution of R commands present in the script file.

R Script File – Example

The following is a simple R Script file named “Example.R” that has instructions to print
“Hello World!” to the console. Use R Studio or any text editor to create a file named
Example.R in your PC to the
console. Use R Studio or any text editor to create a file named Example.R in your PC .
Example.R
# R program to print Hello
World aString = “Hello World!”
print ( aString)
output:

 R treats the hashtag character, #, in a special way The hashtag is known


as the commenting symbol in R

Run R Script File

R language provides an R Interpreter. It can be invoked using the command Rscript in the
terminal. To run an R script file Example.R in the Terminal command prompt, use the
following syntax.

$ Rscript Example.R
Open a Terminal from the location of Example.R and run the following command in the
Terminal.

Entering Commands

 R is a command line driven program. The user enters commands at the prompt (> by
default) and each command is executed one at a time
Example:
>4+4
Output:

 When you type a command at the prompt and hit Enter, your computer executes the
command and shows you the results. Then RStudio displays a fresh prompt for your
next command. For
Example: if you type 1 + 1 and hit Enter, RStudio will display
Output:

 If you type an incomplete command and press Enter, R will display a + prompt, which
means it is waiting for you to type the rest of your command. Either finish the command or
hit Escape to start over:
Output:

 If you type a command that R doesn’t recognize, R will return an error message. If you
ever see an error message, don’t panic. R is just telling you that your computer couldn’t
understand or do what you asked it to do. You can then try a different command at the next
prompt:
Output:

working of variables in R

Variable Assignment:The variables can be assigned values using leftward, rightward and equal
to operator. The values of the variables can be printed using print() or cat() function. The cat()
function combines multiple items into a continuous print output.

# Assignment using equal operator.

var.1 = c(0,1,2,3)

# Assignment using leftward operator.

var.2 <-c(“learn”,”R”)
# Assignment using rightward operator.

c(TRUE,1) ->var.3

• Data Type of a Variable

• In R, a variable itself is not declared of any data type, rather it gets the data type of the R -
object assigned to it. So R is called a dynamically typed language, which means that we can change
a variable’s data type of the same variable again and again when using it in a program.

• Class(variable_name)--à gives data type of variable

• Ex:

dat<-5

dat1<-3.234

dat2<-“program”

class(dat)

class(dat1)

class(dat2)

Output:

• Finding Variables

To know all the variables currently available in the workspace we use the ls() function. Also the ls()
function can use patterns to match the variable names. rm() is used to remove a variable

EX:-

ls()

Output:

• Ex: To remove variable we use

rm()
rm(dat)

Output:

R - Data Types

Data Type Example

Numeric 12.3, 5, 999

Integer 2L, 34L, 0L

Complex 3 + 2i

Character “a”, “good”, “TRUE”, “23.4”

Logical TRUE ,FALSE

Raw Raw Values

Program:

V<- TRUE

print(class(v))

v1 <- 23.5

print(class(v1))

v2<- 2L

print(class(v2))

v3<- 2+5i

print(class(v3))

v4 <-“TRUE”

print(class(v4))

v5<-charToRaw(“SACET”)

print(v5)

print (class(v5))

Output:
Experiment-2

AIM:

a)Implement R script to show the usage of various operators available in R language.

b)Implement R script to read person’s age from keyboard and display whether he is eligible
for voting or not.

c)Implement R script to find biggest number between two

numbers. d)Implement R script to check the given year is leap year

or not.
a)

R Operators

There are four main categories of Operators in R programming language. They are shown in the following picture:

We shall learn about these operators in detail with Example R programs.

R Arithmetic Operators

Arithmetic Operators are used to accomplish arithmetic operations. They can be operated on the basic data types
Numericals, Integers, Complex Numbers. Vectors with these basic data types can also participate in arithmetic operations,
during which the operation is performed on one to one element basis.
Operator Description Usage

+ Addition of two operands a+b

– Subtraction of second operand from first a–b

* Multiplication of two operands a*b

/ Division of first operand with second a/b

%% Remainder from division of first operand with second a %% b

%/% Quotient from division of first operand with second a %/% b

^ First operand raised to the power of second operand a^b

An example for each of the arithmetic operator on Numerical values is provided below :

Example program:-

print ( a+b ) #addition print


( a-b )#subtraction print
( a*b )#multiplication print
( a/b ) #Division print ( a%
%b )#Reminder print ( a
%/%b )#Quotient print (
a^b ) #Power of

Output:-

An example for each of the arithmetic operator on Vectors is provided below :


Example Program:

a <- c(8, 9, 6)
b <- c(2, 4, 5)

print (a+b) #addition


print (a-b) #subtraction

print (a*b) #multiplication

print (a/b) #Division


print (a%%b) #Reminder
print (a%/%b) #Quotient
print (a^b) #Power of

Output:-

Relational Operators are those that find out relation between the two operands provided to them. Following are the six
relational operations R programming language supports.The output is boolean (TRUE or FALSE) for all of the
Relational Operators in R programming language.
Operator Description Usage

< Is first operand less than second operand a<b

> Is first operand greater than second operand a>b

== Is first operand equal to second operand a == b

<= Is first operand less than or equal to second operand a <= b

>= Is first operand greater than or equal to second operand a>=


b
!= Is first operand not equal to second operand a!=b

An example for each of the relational operator on Numberical values is provided below :

r_op_relational.R R Script File:-

Output:-

An example for each of the relational operator on Vectors is provided below :

r_op_relational_vector.R R Script File:-


# R Operators - R Relational Operators Example for Numbers

a <- c(7.5, 3, 5)
b <- c(2, 7, 0)

print ( a<b ) # less than


print ( a>b ) # greater than
print ( a==b ) # equal to
print ( a<=b ) # less than or equal to
print ( a>=b ) # greater than or equal to
print ( a!=b ) # not equal to

Output:-

Logical Operators in R programming language work only for the basic data types logical, numeric and complex and
vectors of these basic data types.

Operator Description Usage

& Element wise logical AND operation. a&b

| Element wise logical OR operation. a|b

! Element wise logical NOT operation. !a

&& Operand wise logical AND operation. a && b

|| Operand wise logical OR operation. a || b

An example for each of the logical operators on Numerical values is provided below :

r_op_logical.R R Script File:-


Output:-

An example for each of the logical operators on Vectors is provided below :

R Script File:-

Output:-
R Assignment Operators

Assignment Operators are those that help in assigning a value to the variable.

Operator Description Usage

= Assigns right side value to left side operand a=3

<- Assigns right side value to left side operand a <- 5

-> Assigns left side value to right side operand 4 -> a

<<- Assigns right side value to left side operand a <<- 3.4

->> Assigns left side value to right side operand c(1,2) ->> a

An example for each of the assignment operators is provided below :

r_op_assignment.R R Script File:-


# R Operators - R Assignment Operators

a=2
print ( a )

a <- TRUE
print ( a )

454 -> a
print ( a )

a <<- 2.9
print ( a )

c(6, 8, 9) -> a
print ( a )

Output:-

These operators does not fall into any of the categories mentioned above, but are significantly important during R
programming for manipulating data.

Operator Description Usage

: Creates series of numbers from left operand to right operand a:b

%in% Identifies if an element(a) belongs to a vector(b) a %in% b

%*% Performs multiplication of a vector with its transpose A %*% t(A)

An example for each of the Miscellaneous operators is provided below :


r_op_misc.R R Script File:-

Output:-

b)R Program Example: How to check Age of a user is eligible for voting or not in R

{
age <- as.integer(readline(prompt = "Enter your age :"))

if (age >= 18) {


print(paste("You are valid for voting :", age))
} else{
print(paste("You are not valid for voting :", age))
}

This is a R program that prompts the user to enter their age and check if they are eligible to vote based on the age
they enter. Here’s what the code does, step by step:

1. The program starts by using the readline() function to prompt the user to enter their age, which is stored
in the variable age. The as.integer() function is used to ensure that the age is stored as an integer.
2. Next, the program uses an if-else statement to check if the age is greater than or equal to 18. If the age is
greater than or equal to 18, it prints a message indicating that the user is valid for voting along with the age.
Else, it prints that the user is not valid for voting.
3. The function paste() concatenates the message string with the age.
4. Finally, when the program runs it will take input from the user and give the output as the eligibility of
voting of the person based on their age.
It’s important to note that different countries have different voting age requirement, in most countries 18 is the age
limit but this may not be the case in every country.

Output:-

c)R Program Example:- How to find the greatest number among three numbers in R .

{
x <- as.integer(readline(prompt = "Enter first number :"))
y <- as.integer(readline(prompt = "Enter second number :"))
z <- as.integer(readline(prompt = "Enter third number :"))

if (x > y && x > z) {


print(paste("Greatest is :", x))
} else if (y > z) {
print(paste("Greatest is :", y))
} else{
print(paste("Greatest is :", z))
}
}

Output:-

Experiment-3

Aim:-

a) Implement R script to generate first N Natural numbers.


b) Implement R script to check given number is palindrome or not.
c) Implement R script to print factorial of a number.
d) Implement R script to check given number is Armstrong or not.

Source Code:-

a)
num = as.integer(readline(prompt="Enter a number: ")
Enter a number:45
if(num < 0) {
print("Enter a positive number")
} else {
sum = 0
# use while loop to iterate until zero
while(num > 0) {
sum = sum + num
num = num - 1
}
print(paste("The sum is",sum))
}

Output:-

b)Example program to print factorial of number

Source code:-

int <- as.integer(readline(prompt = "Please enter a number"))


facto <- 1
if (int < 0) {
print("Negative numbers are not allowed")
}else if (int == 0) {
print("The factorial of 0 is 1")
} else {
facto <- factorial(int)
print(facto)
}
Output:-

c)Example program to check given number is palindrome or not.

Source code:-

n<-readline(prompt=”please enter any integer value:”)


please enter any integer value:45
n<-as integer(n)
num<-n
rev<-0
while(n!=0){
rem<-n%%10
rev<-rem+(rev*10)
n<-as.integer(n/10)
}
Print(rev)
If(rev==num){
Cat (num,”is a palindrome number”)
}else{
Cat(numm,”is not a palindrome number”)
}

Output:-

d) Example program to check given number is Armstrong or not.

Source code:-

num = as.integer(readline(prompt="Enter a number: "))


Enter a number:153
sum = 0
temp = num
while(temp > 0) {
digit = temp %% 10
sum = sum + (digit ^ 3)
temp = floor(temp / 10)
}
if(num == sum) {
print(paste(num, "is an Armstrong number"))
} else {
print(paste(num, "is not an Armstrong number"))
}

Output:-
Experiment-4
Aim:

a) Implement R script to perform various operations on string using string libraries

b) Implement R script to check given string is palindrome or not

c) Implement R scripts to accept line of text and find the number of characters, number of
vowels and number of blank spaces in it.

d) Implement R script for Call-by-Value and Call-by-reference

Source Code:-

a)
library(stringr)
my_string <- "The quick brown fox jumps over the lazy dog"
str_to_lower(my_string)
str_to_upper(my_string)
str_extract(my_string, "brown")
str_trim(my_string)
str_split(my_string, " ")
str_replace(my_string, "fox", "cat")
Output:-

b)Example program to check given string is palindrome or not.

Source Code:-
is_palindrome <- function(string) {
reversed_string <- rev(strsplit(string, "")[[1]])
identical(reversed_string, strsplit(string, "")[[1]])
}
is_palindrome("racecar") # should return TRUE
is_palindrome("hello") # should return FALSE
is_palindrome("A man a plan a canal Panama") # should return TRUE

Output:-

c)Source Code:-

cat("Enter a line of text: ")


text <- readLines("stdin")
num_chars <- nchar(text)
num_vowels <- length(grep("[aeiouAEIOU]", text))
num_spaces <- length(grep("\\s", text))
cat("Number of characters:", num_chars, "\n")
cat("Number of vowels:", num_vowels, "\n")
cat("Number of blank spaces:", num_spaces, "\n")

Output:-

d)R Script of Call-by-Value and Call-by-Reference

Source Code:-

increment_val <- function(val) {


val <- val + 1
cat("Inside function: ", val, "\n")
}
increment_ref <- function(ref) {
ref$val <- ref$val + 1
cat("Inside function: ", ref$val, "\n")
}
val <- 5
increment_val(val)
cat("Outside function: ", val, "\n")
ref <- list(val = 5)
increment_ref(ref)
cat("Outside function: ", ref$val, "\n")
In the increment_val function, a copy of the val argument is made and manipulated inside the function.
The original value outside the function is not affected. This is a call-by-value mechanism.

In the increment_ref function, a reference to a list object ref is passed as an argument. The val member
of the list is manipulated inside the function and the change is reflected outside the function. This is a
call-by-reference mechanism.

Output:-

Experiment-5

Aim:-
a)Implement R script to create a list.
b)Implement R script to access elements in the list.
c)Implement R script to merge two or more lists. Implement R scripts to perform matrix
operation.

Source Code:-
a) R script to create a list:
my_list <- list("apple", "banana", "cherry", 1, 2, 3)
print(my_list)
Output:-

b)R script to access elements in list

Source code:-
my_list <- list("apple", "banana", "cherry", 1, 2, 3)
print(my_list[[1]]) # Accessing the first element in the list
print(my_list[[3]]) # Accessing the third element in the list
Output:-
c)R script to merge two or more lists and
matrix operation

Source Code:-

list1 <- list("apple", "banana", "cherry")


list2 <- list(1, 2, 3)
merged_list <- c(list1, list2)
print(merged_list)
Output:-

Source Code:-
#matrix operations in R
mat1 <- matrix(c(1, 2, 3, 4), nrow=2, ncol=2)
mat2 <- matrix(c(5, 6, 7, 8), nrow=2, ncol=2)
mat_add <- mat1 + mat2
print(mat_add)
mat_mult <- mat1 %*% mat2
print(mat_mult)

Output:
Experiment-6
Aim:-

d)Implement R script to perform various operations on vectors.


e)Finding the sum and average of given numbers using arrays.
f)To display elements of list in reverse order.
g)Finding the minimum and maximum elements in the array.

Source Code:-

d)
vec1 <- c(1, 2, 3, 4, 5)
vec2 <- c(6, 7, 8, 9, 10)
vec_sum <- vec1 + vec2
print(vec_sum)
vec_diff <- vec1 - vec2
print(vec_diff)
vec_prod <- vec1 * vec2
print(vec_prod)
vec_div <- vec1 / vec2
print(vec_div)
vec_dot_prod <- sum(vec1 * vec2)
print(vec_dot_prod)
vec_cross_prod <- crossprod(vec1, vec2)
print(vec_cross_prod)
Output:-

e)Example program for finding sum and average of given numbers using arrays.

Source code:-
num_array <- array(c(1, 2, 3, 4, 5), dim = c(1, 5))
array_sum <- sum(num_array)
print(array_sum)
array_avg <- mean(num_array)
print(array_avg)
Output:-
f)Example program to display elements of list in reverse order.

Source Code:-

my_list <- list("apple", "banana", "orange", "pear")


rev_list <- rev(my_list)
print(rev_list)
Output:-

g)Example program for finding maximum and minimum elements in array.

Source Code:-

num_array <- array(c(1, 2, 3, 4, 5), dim = c(1, 5))


array_min <- min(num_array)
print(array_min)
array_max <- max(num_array)
print(array_max)
Output:-

You might also like