#R solutions for in-class tasks. MAS115 Sem 2, Lab Class 1
## Solutions to 3.4 tasks
#1.
Score <- 10.4
#2.
isMale <- TRUE
#3.
Name <- "Tim"
#4.
is.vector(Score)
#5.
Pest <- rep(c("A", "B"), c(3,7))
#6.
# Using the paste command, which basically adds together character vectors.
# For example try looking at the output of
paste("Axis", c("x", "y", "z"))
# You should see that this gives you a character vector of length 3,
# where Axis has had either x, y or z added to it.
# Note the recycling of the vector of length 1 i.e. "Axis"
# to fit the length of c("x", "y", "z").
# Hence to get the output asked for Flower you can use
Flower <- paste("Helianthus", rep(c("debilis", "annuus"), c(8,2)))
Flower
## Solutions to 3.6 tasks
#1.
set.seed(1)
height <- sample(150:160, size = 10, replace = TRUE)
height
#2.
# For example, try the followng.
# Every sample command here is identical!
set.seed(1)
sample(0:9,size=6,replace=FALSE)
sample(0:9,size=6,replace=FALSE)
set.seed(1)
sample(0:9,size=6,replace=FALSE)
sample(0:9,size=6,replace=FALSE)
# What do you notice?
set.seed(NULL)
sample(0:9,size=6,replace=FALSE)
sample(0:9,size=6,replace=FALSE)
set.seed(NULL)
sample(0:9,size=6,replace=FALSE)
set.seed(2)
sample(0:9,size=6,replace=FALSE)
sample(0:9,size=6,replace=FALSE)
set.seed(2)
sample(0:9,size=6,replace=FALSE)
set.seed(1)
sample(0:9,size=6,replace=FALSE)
#3.
# Experiment with just giving a single number for the first argument,
# and with omitting the size argument.
# For coin tosses
sample(c("Heads","Tails"),size=20,replace=TRUE)
# For a biased coin, e.g. with probability of heads 0.4
sample(c("Heads","Tails"),size=20,prob=c(0.4,0.6),replace=TRUE)
## Solutions to 3.9 tasks
#1.
# Why is the command a+1 an example of recycling?
# Answer: because a is of length 3, and the value 1 is of length 1
# Hence R cycles through 1 three times.
#2.
# Comparisons - just use a standard operator e.g. <, >, == and take
# advantage of the fact that R can vectorise things for you.
isTall <- height >= 155
isTall
#3.
height[isTall] # produces a vector of just the numbers >= 155
#4.
# Create a vector Aheight to contain just those values in vector 'height'
# that have corresponding 'Flower' value "Helianthus annuus".
Flower # show what was created in Tasks 3.6 Q6
(Aheight <- height[Flower == "Helianthus annuus"])
#5.
#a) First 100 even numbers in order
(Even=seq(from=2,to=200, by=2))
#b) Create subvector EvNoFirst which has removed 1st element of Even
(EvNoFirst <- Even[-1])
#c) Create subvector EvNoLast which has removed last element of Even
(EvNoLast <- Even[-100])
#d) Calculate the difference EvNoFirst - EvNoLast
EvNoFirst - EvNoLast
# all 2's
#6.
# For example
set.seed(0)
coins <- sample(c("Heads","Tails"),size=20,replace=TRUE)
table(coins)
# table counts up the number of times that each value occurs