Test 1
Test 1
Vectors (3 questions)
5. Question: Create a vector in R containing the numbers 10, 20, 30, 40, and
50. Display its content.
6. Question: How can you access the third element of a vector `v <- c(1, 2, 3,
4, 5)` in R? Write the R code.
7. Question: Write an R code to create a vector of 5 random integers between 1
and 100 and find the mean of these numbers.
Lists (3 questions)
8. Question: Create a list in R that contains the following elements: a string
("hello"), a numeric vector (1, 2, 3), and a logical value (`TRUE`).
9. Question: How would you extract the second element of the list `mylist <-
list(a = 1:3, b = "hello", c = TRUE)`? Write the R code.
10. Question: Demonstrate how to update the first element of a list `mylist` to
`FALSE`.
Matrices (3 questions)
11. Question: Create a 3x3 matrix in R with values from 1 to 9, and then
display it.
12. Question: How do you access the element in the second row and third column
of a matrix `m <- matrix(1:9, nrow=3, ncol=3)`? Write the R code.
13. Question: Write an R code to multiply two matrices, `A <- matrix(1:4,
nrow=2)` and `B <- matrix(5:8, nrow=2)`.
Arrays (2 questions)
17. Question: Create a 2x2x2 array in R with the numbers 1 to 8. Display the
array.
18. Question: How would you access the element in the first row, second column,
and first slice of a 3D array `arr <- array(1:9, dim=c(3,3,1))`? Write the R code.
Factors (2 questions)
19. Question: Create a factor in R for the days of the week: Monday, Tuesday,
Wednesday, Thursday, and Friday. Display the factor.
20. Question: Write an R function that takes a factor variable and returns the
levels of the factor.
ANSWERS:
1)R.version
2) a<-20
b<-30
c<-a+b
print(c)
5)v<-c(10,20,30,40,50)
print(v)
7)v<-sample(1:100,5)
print(v)
mean(v)
8)lis<-list("hello",c(1,2,3),TRUE)
print(lis)
9)
mylist <- list(a = 1:3, b = "hello", c = TRUE)
mylist$b
11)mat<-matrix(1:9,nrow=3,ncol=3)
print(mat)
12)mat<-matrix(1:9,nrow=3,ncol=3)
print(mat)
mat[2,3]
16)
17)a<-array(1:8, dim=c(2,2,2))
print(a)
18)a<-array(1:8, dim=c(2,2,2))
print(a)
print(a[1,2,1])
20)
days<-factor(c("monday", "tuesday", "wednesday", "thursday","friday"))
get_levels<-function(days){
Levels(days)
}