EXERCISE
TOPIC: BASIC BUILDING BLOCKS
Questions- Write down the code or output
1.
Perform the calculations in a single line in RStudio. a.
Add 8 and 16
b.
Subtract the answer by 9
c.
Divide the answer by 10
Store the output in a variable x. Print out x.
Answer: x = ((8 + 16)-9)/10 x
2.
Create two vectors:
x : 1,2,3,4,5
y: 2,4,6
Combine x, y, and the number 10 in one vector. Store the new combined vector in a variable z. Answer:
x = c(1,2,3,4,5)
y = c(2,4,6)
y = append(y,10)
z = append(x,y)
z
3.
Add the x and y vectors created above, and store the value in p, what would be the value of p?
Answer:
max_length = max(length(x), length(y))
pad_vector = function(vec, len)
{ c(vec, rep(NA, len - length(vec)))
}
padded_x = pad_vector(x, max_length)
padded_y = pad_vector(y, max_length)
p = mapply(function(a,b)ifelse(is.na(a) | is.na(b), NA, a+b), padded_x, padded_y)
p
I added a small function to check the relative lengths of the vector, it then pads the shorter one to match the length of the longer one. The mapply function adds NA to the shorter one to match
the lengths. I did it this way to avoid repetition.
Value of P = 3 6 9 14 NA