Chapter 3.1.1 Exercises
In [22]:
i39 <- sapply(3:9, seq) # list of vectors
sapply(i39, fivenum)
In [7]:
vapply(i39, fivenum,
c(Min. = 0, "1st Qu." = 0, Median = 0, "3rd Qu." = 0, Max. = 0))
In [63]:
# sapply(*, "array") -- artificial example
(v <- structure(10*(5:8), names = LETTERS[1:4]))
f2 <- function(x, y) outer(rep(x, length.out = 3), y)
(a2 <- sapply(v, f2, y = 2*(1:5), simplify = "array"))
# wtf?
In [14]:
a.2 <- vapply(v, f2, outer(1:3, 1:5), y = 2*(1:5))
stopifnot(dim(a2) == c(3,5,4), all.equal(a2, a.2),
identical(dimnames(a2), list(NULL,NULL,LETTERS[1:4])))
hist(replicate(100, mean(rexp(10))))
In [19]:
# However, we can do what we want to do by using mapply().
mapply(sumsq, 1:10, 1:10, MoreArgs = list(x = x))
In [5]:
mapply(function(x, y) seq_len(x) + y,
c(a = 1, b = 2, c = 3), # names from first
c(A = 10, B = 0, C = -10))
In [6]:
word <- function(C, k) paste(rep.int(C, k), collapse = "")
utils::str(mapply(word, LETTERS[1:6], 6:1, SIMPLIFY = FALSE))
In [14]:
# Unfortunately, there are NAs in the data so we cannot simply take the means of those variables. However, we can tell the colMeans function to remove the NAs before computing the mean.
sapply(s, function(x) {
colMeans(x[, c("Ozone", "Solar.R", "Wind")],
na.rm = TRUE)
})
In [16]:
# With multiple factors and many levels, creating an interaction can result in many levels that are empty.
str(split(x, list(f1, f2)))
In [17]:
# We can also take the group means without simplifying the result, which will give us a list. For functions that return a single value, usually, this is not what we want, but it can be done.
tapply(x, f, mean, simplify = FALSE)