This is the Lab 1 practice for subject WQD7004 Programming for Data Science in University of Malaya, Semester 1 2025/2026.
Create a vector named num with four elements (2, 0, 4, 6).
num <- c(2,0,4,6)
num[3]
## [1] 4
num[-1]
## [1] 0 4 6
length(num)
## [1] 4
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
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"
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
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
sum(x)
## [1] 25
round(mean(x),2)
## [1] 6.25
min(x)
## [1] 4
max(x)
## [1] 8
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
y <- c(x[1:2],x[(length(x)-1):length(x)])
print(y)
## [1] 7 6 15 17
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
s1[length(x)-1]
## [1] 15
s2[2]
## [1] 15
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:
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")