Practice 1 BASIC BUILDING BLOCKS _ Vectors

.docx

School

University of Illinois, Urbana Champaign *

*We aren’t endorsed by this school

Course

557

Subject

Mathematics

Date

Feb 20, 2024

Type

docx

Pages

3

Uploaded by MegaRose12943

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
4. Find the square root of vector x . k = sqrt(x) k = [1] 1.000000 1.414214 1.732051 2.000000 [5] 2.236068 5. What would be the output of the following code? > x <- 1:4 > y <- 6:9 > z <- x + y > z Choice: 7 9 11 13 7 9 11 13 14 9 11 13 Answer: 7 9 11 13 6. Create vectors: x: 1,2,3,4,5 y: 2,3,4 Subtract vector x from y. Print the output. Explain Answer: x = 1:4 y = 6:9 z = x+y z ##Sixth Question## x = c(1,2,3,4,5) y = c(2,3,4) 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 -1 -1 -1 NA NA
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
  • Access to all documents
  • Unlimited textbook solutions
  • 24/7 expert homework help