This is the Lab 1 practice for subject WQD7004 Programming for Data Science in University of Malaya, Semester 1 2025/2026.

Q2

Create a vector named num with four elements (2, 0, 4, 6).

num <- c(2,0,4,6)
  1. Display the third element of the vector.
num[3]
## [1] 4
  1. Display the all elements of the vector except first element.
num[-1]
## [1] 0 4 6
  1. Count the number of elements in the vector.
length(num)
## [1] 4

Q3

Create a vector named q3 that add two numbers 3 and 5. After that, add 100 to this vector and display the output.

q3 <- 3 + 5
q3 <- q3 + 100
print(q3)
## [1] 108

Q4

Create a vector named animal that consists of cat, tiger, lion and elephant. Display the vector.

animal <- c("cat","tiger","lion","elephant")
print(animal)
## [1] "cat"      "tiger"    "lion"     "elephant"

After that, append monkey and cow to the vector and display the output.

animal <- append(animal, c("monkey","cow"))
print(animal)
## [1] "cat"      "tiger"    "lion"     "elephant" "monkey"   "cow"

(another solution)

animal <- c(animal,"snake","lamb")
print(animal)
## [1] "cat"      "tiger"    "lion"     "elephant" "monkey"   "cow"      "snake"   
## [8] "lamb"

Q5

Create two vectors named n1 and n2 of integers type (any number) and of length 3. Then, add and multiply the two vectors.

n1 <- c(7L, 14L, 1L)
n2 <- c(3L, 2L, 11L)
addition <- n1 + n2
print(addition)
## [1] 10 16 12
multiplication <- n1 * n2
print(multiplication)
## [1] 21 28 11

Q6

Create a vector x of size 4 with any value from 1-10.

x <- c(7, 6, 8, 4)
print(x)
## [1] 7 6 8 4
  1. Display the sum, mean, minimum and the maximum of the vector x. *mean in two decimal places.
sum(x)
## [1] 25
round(mean(x),2)
## [1] 6.25
min(x)
## [1] 4
max(x)
## [1] 8
  1. Append 3 values (11-20) to the vector x created. Display the sum, mean, minimum and the maximum of the vector.
x <- append(x, c(13,15,17))
sum(x)
## [1] 70
round(mean(x),2)
## [1] 10
min(x)
## [1] 4
max(x)
## [1] 17
  1. Display the first two values and last two values of vector x.
y <- c(x[1:2],x[(length(x)-1):length(x)])
print(y)
## [1]  7  6 15 17
  1. Assign the vector x in ascending order to s1, descending order to s2 and reverse order to s3.
s1 <- sort(x)
s1
## [1]  4  6  7  8 13 15 17
s2 <- sort(x, decreasing = TRUE)
s2
## [1] 17 15 13  8  7  6  4
s3 <- rev(x)
s3
## [1] 17 15 13  4  8  6  7
  1. Display the second highest value in vector x.
s1[length(x)-1]
## [1] 15
s2[2]
## [1] 15

Q7

Create an R file named total.r that get two integer input from user. Display the total of the input. Run the r file using terminal. Example output: Lab1 Q7 Example Output

cat("Enter two number : \n")
input <- readLines("stdin",2)
num1 <- as.integer(input[1])
num2 <- as.integer(input[2])
total <- num1 + num2
cat(paste(num1, " + ", num2 , " = ", total), "\n")