0% found this document useful (0 votes)
72 views17 pages

R Lab Assignment

Assignment of R

Uploaded by

tapstaps902
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)
72 views17 pages

R Lab Assignment

Assignment of R

Uploaded by

tapstaps902
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/ 17

Experiment No 1

Name: Tohidealam Firoj Nadaf


Branch: B.Tech AIML – B
Roll no: 97

a) Implement the All Basic Operations (Arithmetic, Logical, Relational &


Assignment etc.) of R programming’s with a different Examples.
# Arithmetic Operations
print("Arithmetic Operations:")
x <- 10
y <- 20
print(paste("Addition: ", x + y))
print(paste("Subtraction: ", x - y))
print(paste("Multiplication: ", x * y))
print(paste("Division: ", x / y))
print(paste("Exponentiation: ", x ^ 2))
print(paste("Modulus: ", x %% 3))
print(paste("Integer Division: ", x %/% 3))

# Logical Operations
print("Logical Operations:")
a <- TRUE
b <- FALSE
print(paste("Logical AND: ", a & b))
print(paste("Logical OR: ", a | b))
print(paste("Logical NOT: ", !a))

# Relational Operations
print("Relational Operations:")
m <- 10
n <- 20
print(paste("Greater than: ", m > n))
print(paste("Less than: ", m < n))
print(paste("Greater than or equal to: ", m >= n))
print(paste("Less than or equal to: ", m <= n))
print(paste("Equal to: ", m == n))
print(paste("Not Equal to: ", m != n))

# Assignment Operations
print("Assignment Operations:")
p <- 30
q <- 40
p <- q
print(paste("Assignment: ", p))

Output:
[1] "Arithmetic Operations:"
> x <- 10
> y <- 20
[1] "Addition: 30"
[1] "Subtraction: -10"
[1] "Multiplication: 200"
[1] "Division: 0.5"
[1] "Exponentiation: 100"
[1] "Modulus: 1"
[1] "Integer Division: 3"

[1] "Logical Operations:"


> a <- TRUE
> b <- FALSE
[1] "Logical AND: FALSE"
[1] "Logical OR: TRUE"
[1] "Logical NOT: FALSE"

[1] "Relational Operations:"


> m <- 10
> n <- 20
[1] "Greater than: FALSE"
[1] "Less than: TRUE"
[1] "Greater than or equal to: FALSE"
[1] "Less than or equal to: TRUE"
[1] "Equal to: FALSE"
[1] "Not Equal to: TRUE"

[1] "Assignment Operations:"


> p <- 30
> q <- 40
> p <- q
> print(paste("Assignment: ", p))
[1] "Assignment: 40"
b) Write a R program to get the first 10 Fibonacci numbers.
# R program to print first 10 Fibonacci numbers
fibonacci <- numeric(10)
fibonacci[1] <- 0
fibonacci[2] <- 1
for(i in 3:10) {
fibonacci[i] <- fibonacci[i-1] + fibonacci[i-2]
}
print("First 10 Fibonacci numbers:")
print(fibonacci)

Output:

[1] "First 10 Fibonacci numbers:"


[1] 0 1 1 2 3 5 8 13 21 34

c) Write a R program to find the datatypes of variables.


# R program to find the datatypes of variables
num <- 10
print(paste("Type of num: ", class(num)))

str <- "Hello, World!"


print(paste("Type of str: ", class(str)))

bool <- TRUE


print(paste("Type of bool: ", class(bool)))

vec <- c(1, 2, 3)


print(paste("Type of vec: ", class(vec)))

df <- data.frame(name = c("Alice", "Bob"), age = c(20, 25))


print(paste("Type of df: ", class(df)))

Output:

[1] "Type of num: numeric"


[1] "Type of str: character"
[1] "Type of bool: logical"
[1] "Type of vec: numeric"
[1] "Type of df: data.frame"
Experiment No 2
Name: Tohidealam Firoj Nadaf
Branch: B.Tech AIML – B
Roll no: 97

a) Write a R program to check if a number is positive or negative using if-


else a statement.
# R program to check if a number is positive or negative
num <- -5 # Change this value to check different numbers

if(num > 0) {
print(paste(num, "is positive"))
} else if(num < 0) {
print(paste(num, "is negative"))
} else {
print("The number is zero")
}

Output:

[1] "-5 is negative"

b) Write a R program to display week days using switch() method


# R program to display week days using switch() method
day_num <- 3 # Change this value to display different weekdays

day <- switch(day_num,


"1" = "Sunday",
"2" = "Monday",
"3" = "Tuesday",
"4" = "Wednesday",
"5" = "Thursday",
"6" = "Friday",
"7" = "Saturday",
"Invalid day number"
)

print(paste("The day is", day))

Output:

[1] "The day is Tuesday"


c) Write an R program to sort a Vector in ascending and descending order.
# R program to sort a vector in ascending and descending order
vec <- c(23, 12, 56, 15, 39, 8, 29)

# Sort in ascending order


asc <- sort(vec)
print("Vector sorted in ascending order:")
print(asc)

# Sort in descending order


desc <- sort(vec, decreasing = TRUE)
print("Vector sorted in descending order:")
print(desc)

Output:

[1] 8 12 15 23 29 39 56
[1] "Vector sorted in descending order:"
[1] 56 39 29 23 15 12 8
Experiment No 3
Name: Tohidealam Firoj Nadaf
Branch: B.Tech AIML – B
Roll no: 97

a) Write an R program to find maximum value in a vector using a for loop.


# R program to find maximum value in a vector using a for loop
vec <- c(23, 12, 56, 15, 39, 8, 29)

# Initialize max_value with the first element of the vector


max_value <- vec[1]

# Loop through the vector


for(i in vec) {
# If the current element is greater than max_value, update max_value
if(i > max_value) {
max_value <- i
}
}

print("Maximum value in the vector:")


print(max_value)

Output:

[1] "Maximum value in the vector:"


[1] 56

b) Write a while loop to find the first occurrence of a specific element in a


vector.
# R program to find the first occurrence of a specific element in a vector
vec <- c(23, 12, 56, 15, 39, 8, 29)
element <- 15 # Change this value to find a different element

# Initialize index to 1
index <- 1

# Loop through the vector


while(index <= length(vec)) {
# If the current element is equal to the target element, break the loop
if(vec[index] == element) {
break
}
# Increment the index
index <- index + 1
}

# Check if the element was found


if(index <= length(vec)) {
print(paste("First occurrence of", element, "is at position", index))
} else {
print(paste(element, "is not in the vector"))
}

Output:

[1] "First occurrence of 15 is at position 4"

c) Write a repeat loop to generate a sequence of numbers.


# R program to generate a sequence of numbers using a repeat loop
num <- 1
repeat {
print(num)
num <- num + 1
if(num > 10) {
break
}
}

Output:

[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
[1] 8
[1] 9
[1] 10
Experiment No 4
Name: Tohidealam Firoj Nadaf
Branch: B.Tech AIML – B
Roll no: 97

a) Write a R program to print only even numbers from a vector of numbers


using next statement.
# R program to print only even numbers from a vector
vec <- c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

for(num in vec) {
# If the number is not divisible by 2 (i.e., it's odd), skip to the next iteration
if(num %% 2 != 0) {
next
}
# If the number is even, print it
print(num)
}

Output:

[1] 2
[1] 4
[1] 6
[1] 8
[1] 10

b) Write a program to check a is divisible by b or not using Function.


is_divisible <- function(a, b) {
if (a %% b == 0) {
return(TRUE)
} else {
return(FALSE)
}
}

print(is_divisible(10, 2)) # This will print TRUE


print(is_divisible(10, 3)) # This will print FALSE

Output:

[1] TRUE
[1] FALSE
c) Write a program to call a Function with Default Argument in R.
power <- function(base, exponent = 2) {
return(base ^ exponent)
}

# Call the function with two arguments


print(power(2, 3)) # This will print 8

# Call the function with one argument (the exponent will default to 2)
print(power(4)) # This will print 16

Output:

[1] 8
[1] 16
Experiment No 5
Name: Tohidealam Firoj Nadaf
Branch: B.Tech AIML – B
Roll no: 97

a) Write a R program to find Sum, Mean and Product of a Vector.


# Define the vector
vec <- c(1, 2, 3, 4, 5)

# Calculate the sum


vec_sum <- sum(vec)
print(paste("Sum of the vector: ", vec_sum))

# Calculate the mean


vec_mean <- mean(vec)
print(paste("Mean of the vector: ", vec_mean))

# Calculate the product


vec_prod <- prod(vec)
print(paste("Product of the vector: ", vec_prod))

Output:

[1] "Sum of the vector: 15"


[1] "Mean of the vector: 3"
[1] "Product of the vector: 120"

b) Write an R Program to Count the Number of Elements, index and access


the values in a Vector.
# Define the vector
vec <- c(10, 20, 30, 40, 50)

# Count the number of elements in the vector


num_elements <- length(vec)
print(paste("Number of elements in the vector: ", num_elements))

# Print the index of the vector


vec_index <- seq_along(vec) - 1 # subtract 1 because R indexing starts from 1
print(paste("Index of the vector: ", vec_index))

# Access the values in the vector


for (i in seq_along(vec)) {
print(paste("Element at index", i-1, "is", vec[i]))
}
Output:

[1] "Number of elements in the vector: 5"


[1] "Index of the vector: 0" "Index of the vector: 1"
[3] "Index of the vector: 2" "Index of the vector: 3"
[5] "Index of the vector: 4"
[1] "Element at index 0 is 10"
[1] "Element at index 1 is 20"
[1] "Element at index 2 is 30"
[1] "Element at index 3 is 40"
[1] "Element at index 4 is 50"

c) Write a R program to Create a list containing strings, numbers, vectors


and a logical # values- do manipulations.
# Create a list
my_list <- list(
strings = c("apple", "banana", "cherry"),
numbers = c(10, 20, 30),
vectors = list(c(1, 2, 3), c(4, 5, 6)),
logical_values = c(TRUE, FALSE, TRUE)
)

# Print the list


print(my_list)

# Access the 'strings' element of the list


print(paste("Strings: ", my_list$strings))

# Access the first 'numbers' element of the list


print(paste("First number: ", my_list$numbers[1]))

# Access the second 'vectors' element of the list


print(paste("Second vector: ", my_list$vectors[[2]]))

# Access the 'logical_values' element of the list


print(paste("Logical values: ", my_list$logical_values))

Output:
$strings
[1] "apple" "banana" "cherry"
$numbers
[1] 10 20 30
$vectors
$vectors[[1]]
[1] 1 2 3
$vectors[[2]]
[1] 4 5 6
$logical_values
[1] TRUE FALSE TRUE
[1] "Strings: apple" "Strings: banana" "Strings: cherry"
[1] "First number: 10"
[1] "Second vector: 4" "Second vector: 5" "Second vector: 6"
[1] "Logical values: TRUE" "Logical values: FALSE"
[3] "Logical values: TRUE"
Experiment No 6
Name: Tohidealam Firoj Nadaf
Branch: B.Tech AIML – B
Roll no: 97

a) Write a program for Array manipulation in R.


# Create an array
array1 <- array(1:12, dim = c(3, 4))
print("Original Array:")
print(array1)

# Add 5 to each element in the array


array1 <- array1 + 5
print("Manipulated Array:")
print(array1)

Output:

[1] "Original Array:"


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

[1] "Manipulated Array:"


[,1] [,2] [,3] [,4]
[1,] 6 9 12 15
[2,] 7 10 13 16
[3,] 8 11 14 17

b) Write a script in R to create two vectors of different lengths and give


these
vectors as input to array and print addition and subtraction of those
matrices.
# Create two vectors of different lengths
vector1 <- c(1, 2, 3, 4, 5, 6)
vector2 <- c(7, 8, 9, 10, 11, 12, 13, 14)

# Convert the vectors into matrices of the same dimensions


matrix1 <- matrix(vector1, nrow = 2, ncol = 3, byrow = TRUE)
matrix2 <- matrix(vector2[1:6], nrow = 2, ncol = 3, byrow = TRUE)

print("Matrix 1:")
print(matrix1)
print("Matrix 2:")
print(matrix2)

# Perform addition and subtraction


sum_matrix <- matrix1 + matrix2
diff_matrix <- matrix1 - matrix2

print("Sum of Matrices:")
print(sum_matrix)

print("Difference of Matrices:")
print(diff_matrix)

Output:

[1] "Matrix 1:"


[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6

[1] "Matrix 2:"


[,1] [,2] [,3]
[1,] 7 8 9
[2,] 10 11 12

[1] "Sum of Matrices:"


[,1] [,2] [,3]
[1,] 8 10 12
[2,] 14 16 18

[1] "Difference of Matrices:"


[,1] [,2] [,3]
[1,] -6 -6 -6
[2,] -6 -6 -6

c) Write a program for Factors in R- do operations.


# Create a vector
data_vector <- c("High", "Medium", "High", "Low", "Medium", "High", "Low", "Low")

# Convert the vector into a factor


data_factor <- factor(data_vector, order = TRUE, levels = c("Low", "Medium", "High"))

print("Factor:")
print(data_factor)

# Print the levels of the factor


print("Levels:")
print(levels(data_factor))

# Print the number of elements in each level


print("Table:")
print(table(data_factor))

# Change the order of the levels


data_factor <- factor(data_factor, levels = c("High", "Medium", "Low"))

print("Reordered Factor:")
print(data_factor)

Output:

[1] "Factor:"
[1] High Medium High Low Medium High Low Low
Levels: Low < Medium < High

[1] "Levels:"
[1] "Low" "Medium" "High"

[1] "Table:"
data_factor
Low Medium High
3 2 3

[1] "Reordered Factor:"


[1] High Medium High Low Medium High Low Low
Levels: High < Medium < Low
Experiment No 7
Name: Tohidealam Firoj Nadaf
Branch: B.Tech AIML – B
Roll no: 97

a) Write an R program to create a Data frames which contain details of 5


employees and display the details in ascending order
# Create a data frame
employee_data <- data.frame(
Employee_ID = c(101, 102, 103, 104, 105),
Employee_Name = c("John", "Sarah", "Mike", "Anna", "Tom"),
Department = c("Sales", "Marketing", "HR", "IT", "Finance"),
Salary = c(50000, 60000, 70000, 80000, 90000),
stringsAsFactors = FALSE
)

print("Original Data Frame:")


print(employee_data)

# Sort the data frame in ascending order by Employee_Name


sorted_data <- employee_data[order(employee_data$Employee_Name), ]

print("Sorted Data Frame:")


print(sorted_data)

Output:

[1] "Original Data Frame:"


Employee_ID Employee_Name Department Salary
1 101 John Sales 50000
2 102 Sarah Marketing 60000
3 103 Mike HR 70000
4 104 Anna IT 80000
5 105 Tom Finance 90000

[1] "Sorted Data Frame:"


Employee_ID Employee_Name Department Salary
4 104 Anna IT 80000
1 101 John Sales 50000
3 103 Mike HR 70000
2 102 Sarah Marketing 60000
5 105 Tom Finance 90000
b) Write a R program to combine a data frame using cbind ().
# Create two data frames
data_frame1 <- data.frame(
Employee_ID = c(101, 102, 103),
Employee_Name = c("John", "Sarah", "Mike"),
stringsAsFactors = FALSE
)

data_frame2 <- data.frame(


Department = c("Sales", "Marketing", "HR"),
Salary = c(50000, 60000, 70000),
stringsAsFactors = FALSE
)

print("Data Frame 1:")


print(data_frame1)

print("Data Frame 2:")


print(data_frame2)

# Combine the data frames using cbind()


combined_data <- cbind(data_frame1, data_frame2)

print("Combined Data Frame:")


print(combined_data)

Output:

[1] "Data Frame 1:"


Employee_ID Employee_Name
1 101 John
2 102 Sarah
3 103 Mike

[1] "Data Frame 2:"


Department Salary
1 Sales 50000
2 Marketing 60000
3 HR 70000

[1] "Combined Data Frame:"


Employee_ID Employee_Name Department Salary
1 101 John Sales 50000
2 102 Sarah Marketing 60000
3 103 Mike HR 70000

You might also like