0% found this document useful (0 votes)
3 views6 pages

lab_taskR

The document contains a series of R programming tasks and solutions, including generating sequences, creating matrices, manipulating strings, and performing mathematical operations. It covers various topics such as accessing matrix elements, finding duplicates, handling missing values, and calculating factorials. Each task is accompanied by R code snippets that demonstrate the implementation of the specified functionality.

Uploaded by

spoorthyvallem
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)
3 views6 pages

lab_taskR

The document contains a series of R programming tasks and solutions, including generating sequences, creating matrices, manipulating strings, and performing mathematical operations. It covers various topics such as accessing matrix elements, finding duplicates, handling missing values, and calculating factorials. Each task is accompanied by R code snippets that demonstrate the implementation of the specified functionality.

Uploaded by

spoorthyvallem
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/ 6

#1).

What is o/p of 1:3 + rep(seq(from=21,by=10,to=91), each=4)

result <- c(1:3, rep(seq(from = 21, by = 10, to = 91), each = 4))


print(result)

#2). Write R code to implement to generate the sequence 1,2,0,4,5,0,7,8,0,10,11,0,


…….49,50
sequence <- c(seq(1, 50, by = 3), rep(0, 2))
print(sequence)

#3.Write R code for the following problem: Create a 2x3 matrix M using R
programming with following speci€cations. Values of the matrix should be randomly
selected between 10 and 30. Elements of the matrix should be arranged in row order.
# Set seed for reproducibility
set.seed(123)

# (a) Create a 2x3 matrix M with values randomly selected between 10 and 30
M <- matrix(sample(10:30, 2*3, replace = TRUE), nrow = 2, byrow = TRUE)
rownames(M) <- c("row1", "row2")
colnames(M) <- c("col1", "col2", "col3")
print("Matrix M:")
print(M)

V <- c(25, 15, 20)

M <- rbind(M, V)
print("Matrix M with vector V added as the third row:")
print(M)

# (b) Access the elements of the matrix using row names and column names
print("Accessing elements using row and column names:")
print(paste("Element at row1, col2:", M["row1", "col2"]))
print(paste("Element at row2, col3:", M["row2", "col3"]))

# (c) Access the element at 2nd column and 4th row


print(paste("Element at 2nd column and 4th row:", M[4, 2]))

# (d) Access only the 3rd row


print("Accessing only the 3rd row:")
print(M[3, ])

# (e) Access only the 2nd column


print("Accessing only the 2nd column:")
print(M[, "col2"])

#4). convert ”is is a fun sentence” to ”is is a great sentence” using gsub in R.
original_string <- "is is a fun sentence"
modified_string <- gsub("fun", "great", original_string)
print(modified_string)

#5). Find Lagged Differences Between Consecutive Elements


vector <- c(3, 7, 11, 15, 19)
lagged_diff <- diff(vector)
print(lagged_diff)

#6). Find Lagged Differences Between Non Consecutive Elements


vector <- c(3, 7, 11, 15, 19)
lagged_diff <- diff(vector,lag=2)
print(lagged_diff)
#7). Write an R program to and the third largest element in a vector
vector <- c(12, 5, 19, 8, 25, 15)
sorted_vector <- sort(vector, decreasing = TRUE)
third_largest <- sorted_vector[3]
print(third_largest)

#8). Write R Program to concatenate the following strings str1=”All the


bset” ,str2=”for”, str3=”mid exam”.
str1 <- "All the best"
str2 <- "for"
str3 <- "mid exam"
result <- paste(str1, str2, str3)
print(result)

#9). write R program to print factorial of a given number using function


factorial <- function(n) {
if (n == 0 || n == 1) {
return(1)
} else {
return(n * factorial(n - 1))
}
}
number <- as.integer(readline(prompt = "Enter a number to calculate its factorial:
"))

cat("Factorial of", number, "is:", factorial(number))

#10). Write R Program to concatenate the following strings str1=”All the


bset” ,str2=”for”, str3=”mid exam” and replace ”mid” with ”semester”
str1 <- "All the best"
str2 <- "for"
str3 <- "mid exam"

concatenated_string <- paste(str1, str2, str3)


final_string <- gsub("mid", "semester", concatenated_string)
print(final_string)

#11. Write a R Program to print the sum of the series 1+11+111+1111+11111+…..


calculate_series_sum <- function(num_terms) {

sum_series <- 0
current_term <- 1

for (i in 1:num_terms) {
sum_series <- sum_series + current_term
current_term <- current_term * 10 + 1
}
return(sum_series)
}

num_terms <- as.integer(readline(prompt = "Enter the number of terms in the series:


"))

result <- calculate_series_sum(num_terms)


print(result)

#12). Write a R Program to print all the perfect numbers in a given Range using
functions.
is_perfect <- function(num) {
sum_of_divisors <- sum(which(num %% 1:(num-1) == 0))
return(sum_of_divisors == num)
}

find_perfect_numbers <- function(start, end) {


perfect_numbers <- c()
for (i in start:end) {
if (is_perfect(i)) {
perfect_numbers <- c(perfect_numbers, i)
}
}
return(perfect_numbers)
}

start_range <- as.integer(readline(prompt = "Enter the start of the range: "))


end_range <- as.integer(readline(prompt = "Enter the end of the range: "))

perfect_numbers_in_range <- find_perfect_numbers(start_range, end_range)


if (length(perfect_numbers_in_range) > 0) {
cat("Perfect numbers in the range", start_range, "to", end_range, "are:",
perfect_numbers_in_range)
} else {
cat("No perfect numbers found in the range", start_range, "to", end_range)
}

#13. For a given vector x < −c(1, 2, 2, 5, 5, 6) extract duplicate elements.


x <- c(1, 2, 2, 5, 5, 6)
duplicates <- x[duplicated(x)]
print(duplicates)

#14. For a given vector x < −c(1, 2, 2, 5, 5, 6) write R command to drop duplicate
elements.
x <- c(1, 2, 2, 5, 5, 6)
unique_elements <- unique(x)
print(unique_elements)

#15. For a given vector y < −c(1, 2, 3, NA) write R command to and the missing
valuesin Y.
y <- c(1, 2, 3, NA)
missing_values <- y[is.na(y)]
print(missing_values)

#16. for a given vector z < −c(15, 20, 32, 45, 59) write R command to recode the
values less than 32 in Z with 99 and the value 32 with NA.
z <- c(15, 20, 32, 45, 59)
z[z < 32] <- 99
z[z == 32] <- NA
print(z)

#17. Write an R program to create a 4 by 4 integer matrix and print the elements in
a matrix that are divisible by 3.
matrix <- matrix(c(1:16), nrow = 4, byrow = TRUE)

cat("Original Matrix:\n")
print(matrix)

# Print the elements divisible by 3


cat("\nElements divisible by 3:\n")
for (i in 1:nrow(matrix)) {
for (j in 1:ncol(matrix)) {
if (matrix[i, j] %% 3 == 0) {
cat(matrix[i, j], "\t")
} else {
cat(" ")
}
}
}

#18. Write R program to solve system of linear equations x + 2y + 3z = 20, 2x + 2y


+ 3z = 100 and 3x + 2y + 8z = 200
m1<-rbind(c(1,2,3),c(2,2,3,),c(3,2,8))
d<-c(20,100,200)
solve(m1,d)

#19. Write R program to add zeros at starting and ending of a numeric vector
num <- c(1, 2, 3, 4, 5)
paste0(0,num,0)

#20. Write R program to generate 40 random variables, uniformly distributed between


-1 and 1.
random_variables <- runif(40, min = -1, max = 1)
print(random_variables)

#21. write R program to remove white spaces in a character vector


char <- c("apple ", " banana", " orange ", " grape ")
print(char)

no_space<- gsub("\\s+", "", char)


print(no_space)

#22. Write R program to count number of words in string.


input_string <- readline(prompt = "Enter a string: ")
words <- strsplit(input_string, "\\s+")[[1]]
num_words <- length(words)
print(num_words)

#23. Write R program to print todays system date.


print(Sys.Date())

#24. write R code for the given problem Assuming students having roll numbers in a
particular class from 1 to 60.The roll numbers of students who are absent for a
particular class on wednesday are
1,2,8,9,11,13,14,17,20,22,24,25,26,29,32,36,45,47,49,50,53,54,58. print the roll
numbers who are present
absent_roll_numbers <- c(1, 2, 8, 9, 11, 13, 14, 17, 20, 22, 24, 25, 26, 29, 32,
36, 45, 47, 49, 50, 53, 54, 58)
all_roll_numbers <- 1:60
present_roll_numbers <- all_roll_numbers[!all_roll_numbers %in%
absent_roll_numbers]
print(present_roll_numbers)

#25. generate the sequence of fractions


limit <- 21
fractions <- numeric()
for (i in seq(1, limit, by = 2)) {
fractions <- c(fractions, 1, 1/i)
}
print(fractions)+

#26. Write R program to generate first 30 prime numbers.


is_prime <- function(n) {
if (n <= 1) {
return(FALSE)
}
for (i in 2:sqrt(n)) {
if (n %% i == 0) {
return(FALSE)
}
}
return(TRUE)
}

prime_numbers <- numeric(30)


count <- 0
i <- 2
while (count < 30) {
if (is_prime(i)) {
count <- count + 1
prime_numbers[count] <- i
}
i <- i + 1
}

print(prime_numbers)

#27. consider the following Data x < −c(2, 2, 6, 7, 8, 6) write R commands for the
following.
x <- c(2, 2, 6, 7, 8, 6)

# (a) Find the indexes of duplicate elements


indexes_of_duplicates <- which(duplicated(x))
print(indexes_of_duplicates)

# (b) Extract duplicate elements in x


duplicate_elements <- x[duplicated(x)]
print(duplicate_elements)

# (c) Extract unique elements in x


unique_elements <- unique(x)
print(unique_elements)

#28. write R code snippets for the following


#(a) Generate sequence of 1 to 10 and append 100 afer 5th item
seq <- 1:10
seq1 <- append(seq, 100, after = 4)
print(seq1)

#(b) create a vector with 10 values and sort them in ascending and descending
order.
vector <- c(5, 2, 9, 3, 7, 1, 8, 4, 10, 6)
ascend <- sort(vector)
descend <- sort(vector, decreasing = TRUE)
print("Sorted in ascending order:")
print(ascend)
print("Sorted in descending order:")
print(descend)

# (c) Add number 7 to a v < −c(1, 2, 3, 4, 5)


v <- c(1, 2, 3, 4, 5)
v1 <- c(v, 7)
print(v1)

#29. consider the following vector x < −c(10, 11, 12, NA, 14, 15, 16, NA, 18, NA,
19) Write R commands for the following
# Given vector
x <- c(10, 11, 12, NA, 14, 15, 16, NA, 18, NA, 19)

# (a) Find the size of a vector and find whether it is a vector or not
vector_size <- length(x)
is_vector <- is.vector(x)

print(paste("Size of the vector:", vector_size))


print(paste("Is it a vector?", is_vector))

# (b) Count the number of 'NA' values


num_na_values <- sum(is.na(x))

print(paste("Number of 'NA' values:", num_na_values))

# (c) Replace all the missing values with Mean of remaining values and print the
updated vector
x_no_na <- x[!is.na(x)] # Extract non-NA values
mean_value <- mean(x_no_na, na.rm = TRUE)
x_updated <- ifelse(is.na(x), mean_value, x)

print("Updated vector:")
print(x_updated)

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