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

Assignment 1: R Programming Please save your R code in a text file v : 2,3,4,5,6

ID: 3869625 • Letter: A

Question

Assignment 1: R Programming

Please save your R code in a text file

v : 2,3,4,5,6,7,4,2

w : 9,10,2,34,5,18,9,2

A) Print the length of the vectors

B) Print all elements of the vectors

C) Print elements at indicies 2 through 4.

D) Print the sum of the elements in each vector.

E) Find the mean of each vector. (Use R's mean() function)

F) Sort the vectors in descending order and then print.

G) Add vectors v and w.

H) Multiply vectors v and w.

I) In vector v select all elements that are greater than 2.

J) In vector w select all elements that are less than 20.

K) Multiply each element of vector v by 6.And then print.

L) Find maximum and minimum of each vector.

M) In each vector, replace all elements with value of 2 by 80.

Explanation / Answer

R code:

v = c(2,3,4,5,6,7,4,2)
w = c(9,10,2,34,5,18,9,2)
# A
print(paste0("Length of vector v = ", length(v) ))
print(paste0("Length of vector w = ", length(w) ))

#B
print("Vector v: ")
for(i in v)
{
print(i)
}
print("Vector w: ")
for(i in w)
{
print(i)
}
#C
print("Vector v elements at index 2 to 4 : ")
cnt <- 2
while (cnt < 5) {
print(v[cnt])
cnt = cnt + 1
}

print("Vector w elements at index 2 to 4 : ")
cnt <- 2
while (cnt < 5) {
print(w[cnt])
cnt = cnt + 1
}

#D
print(paste0("sum of elements of vector v = ", sum(v) ))
print(paste0("sum of elements of vector w = ", sum(w) ))

#E
print(paste0("Mean of vector v = ", mean(v) ))
print(paste0("Mean of vector w = ", mean(w) ))

#F
print("vector v in sorted order")
vtmp = sort(v)
for(i in vtmp)
{
print(i)
}

print("vector w in sorted order")
wtmp = sort(w)
for(i in wtmp)
{
print(i)
}

#G
print("sum of vector v and w")
v + w
#H
print("Product of vector v and w")
v*w

#I) In vector v select all elements that are greater than 2.
print("Elements greater than 2 in vector v")
v[which(v > 2)]

#J) In vector w select all elements that are less than 20.
print("Elements less than 20 in vector w")
w[which(w < 20)]

#K) Multiply each element of vector v by 6.And then print.
print("Multiplied each element of vector v by 6")
v*6
#L) Find maximum and minimum of each vector.
print(paste0("Max of vector v = ", max(v) ))
print(paste0("Min of vector v = ", min(v) ))
print(paste0("Max of vector w = ", max(w) ))
print(paste0("Min of vector w = ", min(w) ))
#M) In each vector, replace all elements with value of 2 by 80.
print("Vector v after raplcaing 2 by 80")
replace(v, v==2, 80)
print("Vector w after raplcaing 2 by 80")
replace(w, w==2, 80)

Sample Output: