Home page

Question 1

x <- 1.1 ; a <- 2.2; b <- 3.3

# a
z <- x^a^b
print(z)
## [1] 3.61714
# b
z <- (x^a)^b
print(z)
## [1] 1.997611
# c
z <- 3*x^3+2*x^2+1
print(z)
## [1] 7.413

Question 2

a <- c(seq(1,8),seq(7,1))
a
##  [1] 1 2 3 4 5 6 7 8 7 6 5 4 3 2 1
b <- rep(seq(5),seq(5)) # the same a rep(c(1,2,3,4,5),c(1,2,3,4,5))
b
##  [1] 1 2 2 3 3 3 4 4 4 4 5 5 5 5 5
c <- rep(seq(5,1),seq(5))
c
##  [1] 5 4 4 3 3 3 2 2 2 2 1 1 1 1 1

Question 3

# creating the random uniform numbers
cart <- runif(2)

# creating polar coords from the cartesian coords
polar <- c(sqrt(cart[1]^2+cart[2]^2),atan(cart[2]/cart[1]))
polar
## [1] 0.6364279 0.7075440

Question 4

# Defining the initial queue
queue <- c('sheep','fox','owl','ant')
queue
## [1] "sheep" "fox"   "owl"   "ant"
# a
queue <- c(queue,'serpent')
queue
## [1] "sheep"   "fox"     "owl"     "ant"     "serpent"

Taking a detour from the homework question to explore the logic of the %in% operator

'sheep' %in% queue # is 'sheep' in vector queue?
## [1] TRUE
queue %in% 'sheep' # is queue in sheep? AKA, for each item in queue, is it in 'sheep'? Basically it is iterating through queue and asking the question is queue[i] in the string (AKA equal to) 'sheep' (could be any other vector as well). Thus, returns an answer for each item in queue
## [1]  TRUE FALSE FALSE FALSE FALSE
queue[c(T,T,T,F,T)] # returns the first, second, third, and fifth element in queue
## [1] "sheep"   "fox"     "owl"     "serpent"
queue[queue %in% 'sheep'] # equal to queue[c(T,F,F,F,F)], since queue %in% 'sheep' returns the vector c(T,F,F,F,F))
## [1] "sheep"
queue[!queue %in% 'sheep'] # equal to queue[c(F,T,T,T,T)] because of the inverse (!) operator
## [1] "fox"     "owl"     "ant"     "serpent"

Now back to the homework

# b
queue <- queue[!queue %in% 'sheep']
queue
## [1] "fox"     "owl"     "ant"     "serpent"
# c
queue <- c('donkey',queue)
queue
## [1] "donkey"  "fox"     "owl"     "ant"     "serpent"
# d
queue <- queue[-5] # or queue[!queue %in% 'serpent'] as done previously; helpful if the index is unknown
queue
## [1] "donkey" "fox"    "owl"    "ant"
# e
queue <-queue[-3]
queue
## [1] "donkey" "fox"    "ant"
# f
queue <- append(queue,'aphid',2)
queue
## [1] "donkey" "fox"    "aphid"  "ant"
# g
which(queue=='ant')
## [1] 4

Question 5

x <- seq(100)
x <- x[x%%2!=0 & x%%3!=0 & x%%7!=0]
x
##  [1]  1  5 11 13 17 19 23 25 29 31 37 41 43 47 53 55 59 61 65 67 71 73 79 83 85
## [26] 89 95 97