Practice 1 BASIC BUILDING BLOCKS _ Vectors
docx
keyboard_arrow_up
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
TOPIC: VECTORS
Questions
1.
Create a vector containing following mixed elements {1, ‘Hi’, 2, ‘Hello’}
Answer:
s = c('1', "hi", '2', "Hello")
s
2.
x <- c(2, 4, 6, 8)
z<- x<1
What is the value of z: Answer:
FALSE FALSE FALSE FALSE
3.
Create a vector named days with seven days of the week. days <- c("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday")
Print only Monday and Wednesday from this vector. Answer:
d = c("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday")
selected_days = d[c(2,4)]
selected_days
4.
(33 < 44) & (3==3)
Is this statement TRUE or FALSE?
Answer: True
5.
(111 >= 111) | !(TRUE)& (5== 5)
Is this statement TRUE or FALSE?
Answer: True
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