Assignment 4

Abigail Griffin

2023-02-03

Daily Assignment 4

1: Assign to the variable n_dims a single random integer between 3 and 10

set.seed(1)
n_dims<-sample(3:10,1)
print(n_dims)
## [1] 3

a: Create a vector of consecutive integers from 1 to n_dims2.

vector<-seq(1:n_dims^2)
print(vector)
## [1] 1 2 3 4 5 6 7 8 9

b: Use the sample function to randomly reshuffle these values.

randomvector <- sample(vector)
print(randomvector)
## [1] 4 7 1 2 5 3 9 6 8

c: create a square matrix with these elements. Print out the matrix.

m<-matrix(data=randomvector, ncol=n_dims)
print(m)
##      [,1] [,2] [,3]
## [1,]    4    2    9
## [2,]    7    5    6
## [3,]    1    3    8

d: find a function in r to transpose the matrix. Transpose flips elements in the matrix. Print it out again and note how it has changed.

t(m)
##      [,1] [,2] [,3]
## [1,]    4    7    1
## [2,]    2    5    3
## [3,]    9    6    8

e: calculate the sum and the mean of the elements in the first row and then the last row.

mdataframe<-data.frame(m)
print(mdataframe)
##   X1 X2 X3
## 1  4  2  9
## 2  7  5  6
## 3  1  3  8
rowSums(mdataframe[1,]) 
##  1 
## 15
rowSums(mdataframe[n_dims,])
##  3 
## 12
rowMeans(mdataframe[1,])
## 1 
## 5
rowMeans(mdataframe[n_dims,])
## 3 
## 4

f: set your code up so you can re-run it to create a matrix of a different size by only changing the n_dims value