LAB – 7 : Vectors, Strings & Data Handling in R
Aim of the Lab
To understand vectors, string manipulation, and basic data handling
operations in R.
Program 1: Create a Vector and Display Elements
Program
v <- c(10, 20, 30, 40, 50)
print(v)
Output
[1] 10 20 30 40 50
Program 2: Find Sum and Mean of a Vector
Program
v <- c(5, 10, 15, 20)
cat("Sum:", sum(v), "\n")
cat("Mean:", mean(v))
Output
Sum: 50
Mean: 12.5
Program 3: Find Maximum and Minimum in a Vector
Program
v <- c(12, 45, 7, 23, 56)
cat("Max:", max(v), "\n")
cat("Min:", min(v))
Output
Max: 56
Min: 7
Program 4: Sort a Vector
Program
v <- c(9, 3, 7, 1, 5)
print(sort(v))
print(sort(v, decreasing = TRUE))
Output
[1] 1 3 5 7 9
[1] 9 7 5 3 1
Program 5: Remove Duplicate Elements
Program
v <- c(1,2,2,3,4,4,5)
print(unique(v))
Output
[1] 1 2 3 4 5
Program 6: Count Frequency of Elements
Program
v <- c(1,2,2,3,3,3,4)
print(table(v))
Output
v
1234
1231
Program 7: String Length and Case Conversion
Program
str <- "R Programming"
cat("Length:", nchar(str), "\n")
cat("Upper:", toupper(str), "\n")
cat("Lower:", tolower(str))
Output
Length: 13
Upper: R PROGRAMMING
Lower: r programming
Program 8: Count Vowels in a String
Program
str <- "education"
vowels <- strsplit(str, "")[[1]]
count <- sum(vowels %in% c("a","e","i","o","u"))
print(count)
Output
[1] 5
Program 9: Reverse a String
Program
str <- "Rstudio"
rev <- paste(rev(strsplit(str, "")[[1]]), collapse = "")
print(rev)
Output
[1] "oidutsR"
Program 10: Check if a String is Palindrome
Program
str <- "madam"
rev <- paste(rev(strsplit(str, "")[[1]]), collapse = "")
if(str == rev)
print("Palindrome")
else
print("Not Palindrome")
Output
[1] "Palindrome"