Question 1:
n_dims <- runif(1, 3, 10)
vec <- c(1:(n_dims^2))
samp <- sample(vec)
m <- matrix(samp, nrow = n_dims, ncol = n_dims)
## Warning in matrix(samp, nrow = n_dims, ncol = n_dims): data length [69] is not a
## sub-multiple or multiple of the number of rows [8]
print(m)
## [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
## [1,] 22 58 3 20 24 44 48 66
## [2,] 41 32 39 35 42 15 1 38
## [3,] 23 45 46 53 36 4 52 49
## [4,] 65 11 19 43 17 50 62 40
## [5,] 69 26 47 12 29 63 2 14
## [6,] 34 59 9 55 51 21 6 64
## [7,] 13 60 33 16 8 10 5 27
## [8,] 68 28 31 30 61 56 37 57
trans_m <- t(m)
print(trans_m)
## [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
## [1,] 22 41 23 65 69 34 13 68
## [2,] 58 32 45 11 26 59 60 28
## [3,] 3 39 46 19 47 9 33 31
## [4,] 20 35 53 43 12 55 16 30
## [5,] 24 42 36 17 29 51 8 61
## [6,] 44 15 4 50 63 21 10 56
## [7,] 48 1 52 62 2 6 5 37
## [8,] 66 38 49 40 14 64 27 57
sum(trans_m[1,])
## [1] 335
mean(trans_m[1,])
## [1] 41.875
sum(trans_m[n_dims,])
## [1] 355
mean(trans_m[n_dims,])
## [1] 44.375
eigen <- eigen(trans_m)
typeof(eigen)
## [1] "list"
Question 2:
r_num <- runif(16)
my_matrix <- matrix(r_num, 4, 4)
r_num2 <- runif(100)
my_logical <- r_num2<50
my_letters <- sample(letters, length(letters))
print(my_letters)
## [1] "e" "u" "h" "z" "d" "t" "a" "x" "p" "s" "v" "q" "o" "b" "n" "c" "j" "i" "w"
## [20] "k" "m" "g" "y" "l" "r" "f"
my_list <- list(my_matrix,my_logical, my_letters)
my_list2 <- list(my_matrix[2,2], my_logical[2], my_letters[2])
sapply(my_list2, typeof)
## [1] "double" "logical" "character"
vec2 <- c(my_matrix[2,2], my_logical[2], my_letters[2])
typeof(vec2)
## [1] "character"
Question 3:
my_unis <- runif(26, 0, 10)
my_letters <- sample(LETTERS, length(LETTERS))
df <- data.frame(my_unis,my_letters)
#for the first variable, use a single line of code in R to select 4 random rows and replace the numerical values in those rows with NA.
df[sample(nrow(df), 4), "my_unis"] <- NA
#for the first variable, write a single line of R code to identify which rows have the missing values.
which(!complete.cases(df$my_unis))
## [1] 1 4 12 17
#re-order the entire data frame to arrange the second variable in alphabetical order
df <- df[order(df$my_letters), ]
#calculate the column mean for the first variable
mean(df$my_unis, na.rm = T)
## [1] 5.21948