Question 1
Here are some vectors about some animals and their properties:
animals <- c("cheetah", "chimpanzee", "lion", "chihuahua", "sloth")
isLazy <- c(FALSE, FALSE, TRUE, FALSE, TRUE)
isAnnoying <- c(FALSE, TRUE, FALSE, TRUE, FALSE)
speed <- c(40, 10, 20, 8, 1)Here are some sub-setting commands:
animals[isAnnoying & speed > 20] #1
animals[isAnnoying | speed > 20] #2
animals[!isLazy & !isAnnoying] #3
speed[isLazy] #4
speed[!isLazy] #5
sum(isLazy) #6
length(isLazy & isAnnoying) #7
length(animals[isLazy & isAnnoying]) #8
For each item below, write the number of the command (there is at most one) that would produce it. If the item cannot be produced by any of the commands, write “none.”
The speeds of the animals that aren’t lazy.
# 5 speed[!isLazy]## [1] 40 10 8The animals that go faster than 20 mph and are also annoying.
# 1 animals[isAnnoying & speed > 20]## character(0)There are no such animals, so we get a character vector of length 0.
How many lazy animals there are.
# 6 sum(isLazy)## [1] 2The reason this works is that the
sum()function coerces theTRUEs to 1s and theFALSEs to 0s before it adds everything up. You can see it in small steps like this:zeroOrOne <- as.numeric(isLazy) zeroOrOne## [1] 0 0 1 0 1sum(zeroOrOne)## [1] 2The lengths of the lazy, annoying animals.
# None! No vector gives the lengths of the animals.You might think that #7 works, but it doesn’t:
length(isLazy & isAnnoying)## [1] 5No animal is both lazy and annoying, so the correct answer is 0. The reason #7 doesn’t work is that
isLazy & isAnnoyingis a combination of vectors of lengh five, so it will be of length five as well.The animals who are annoying or who go faster than 20mph.
# 2 animals[isAnnoying | speed > 20]## [1] "cheetah" "chimpanzee" "chihuahua"How many lazy, annoying animals there are.
# 8 length(animals[isLazy & isAnnoying])## [1] 0
Question 2
For each of the following two items, write a sub-setting command that would produce it:
The animals that go between 5 and 15 miles per hour.
Here’s one way to do it:
animals[speed > 5 & speed < 15]## [1] "chimpanzee" "chihuahua"The number of non-annoying animals:
Here is one way to do it:
sum(!isAnnoying)## [1] 3Here’s another way that is a bit more verbose:
length(animals[!isAnnoying])