Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

R STUDIO The R file will consist of all the code and should be executable (you s

ID: 3751410 • Letter: R

Question

R STUDIO

The R file will consist of all the code and should be executable (you should use R script).

Copy your R script into a word document, submit both R, and word (doc/docx) files.

All the answers, other than the actual codes, are to be noted as comments

Name the file “LastName_Assignment1” with appropriate file extension (.doc and .R)

Your script should follow the format below:

#1 Basic operations, assignments

#a

x <- 4

y <- 5

z <- x+y

z

#output: 9

#b

x <- 1

y <- 5

z <- x+y

z

Question 1: Matrices

a. Provide the code to create matrix X

X = 2 5 8

3 6 9

4 7 10

b. Provide the code to assign the value 2 for all the elements in the matrix that are less than 5

c. Assign the values in 2nd and 3rd column to the new matrix Y

d. Assign row names of X as R1, R2, R3

e. Assign column names of X as C1 to C3

f. Add a new row named R4 with the following values of 3, 6, 9

g. Add a new column named C4 with the following values of 1,3,5,7

h. Assign 0s for all elements of the second column C2

i. Print the final X matrix

Explanation / Answer

####################################
#1 Basic operations, assignments
####################################
#a

x <- 4
y <- 5
z <- x+y
z

#output: 9

#b

x <- 1
y <- 5
z <- x+y
z

#output: 6


####################################
# Question 1
####################################

########## a

x<- c(2,5,8,3,6,9,4,7,10) # create a vector x using function c()
# create matrix using vector x and here we want elements to arrange row wise

x<- matrix(x,nrow=3,byrow=TRUE)

x     # print matrix x
  

########## b
#if value is less than 5 , make it a s 2
for(row in 1:nrow(x)) {
for(col in 1:ncol(x)) {
    if (x[row,col]<5){
      x[row,col]=2
    }
}
}
x


######### c
#indexing in R start from 1. Here we use slice of matrix x to assign to matrix y
y=x[,2:3]
y


######### d
# rownames() function is used to add row names. a vector of rownames is used for this purpose
rownames(x)<-c("R1","R2","R3")
x

######### e
# colnames() function is used to add row names. a vector of colnames is used for this purpose
colnames(x)<-c("C1","C2","C3")
x

######### f

#rbind is used to append a row to the existing matrix

x<-rbind(x,R4=c(3,6,9))
x

######### g
x<-cbind(x,c4=c(1,3,5,7))
x

######### h
for(row in 1:nrow(x)) {
x[row,2]=0
}
x

######### i
#final matrix is
x