
2 minute read
Classes�������������������������������������������������������������������������������������������������������������������������
Chapter 9 ■ advanCed r programming
## [1] 1 1 ## [1] 2 2 ## [1] 3 3 ## [1] 4 4 ## [1] 5 5 ## [1] 6 6
Advertisement
So what happens if the function to apply takes arguments besides those you get from the matrix?
sumpow <- function(x, n) sum(x) ** n apply(m, 1, sumpow) ## Error in FUN(newX[, i], ...): argument "n" is missing, with no default
If it does, you can give these arguments as additional arguments to apply; they will be passed on to the function in the order you give them to apply.
apply(m, 1, sumpow, 2) ## [1] 36 225
It helps readability a lot, though, to explicitly name such parameters.
apply(m, 1, sumpow, n = 2) ## [1] 36 225
lapply
The lapply function is used for mapping over a list. Given a list as input, it will apply the function to each element in the list and output a list of the same length as the input containing the results of applying the function.
(l <- list(1, 2, 3)) ## [[1]] ## [1] 1 ## ## [[2]] ## [1] 2 ## ## [[3]] ## [1] 3 lapply(l, function(x) x**2) ## [[1]] ## [1] 1 ## ## [[2]] ## [1] 4 ## ## [[3]] ## [1] 9
If the elements in the input list have names, these are preserved in the output vector.
240
Chapter 9 ■ advanCed r programming
l <- list(a=1, b=2, c=3) lapply(l, function(x) x**2) ## $a ## [1] 1 ## ## $b ## [1] 4 ## ## $c ## [1] 9
If the input you provide is a vector instead of a list, it will just convert it into a list, and you will always get a list as output.
lapply(1:3, function(x) x**2) ## [[1]] ## [1] 1 ## ## [[2]] ## [1] 4 ## ## [[3]] ## [1] 9
Of course, if the elements of the list are more complex than a single number, you will still just apply the function to the elements.
lapply(list(a=1:3, b=4:6), function(x) x**2) ## $a ## [1] 1 4 9 ## ## $b ## [1] 16 25 36
sapply and vapply
The sapply function does the same as lapply, but tries to simplify the output. Essentially, it attempts to convert the list returned from lapply into a vector of some sort. It uses some heuristics for this and guesses as to what you want as output, simplifies when it can, but gives you a list when it cannot figure it out.
sapply(1:3, function(x) x**2) ## [1] 1 4 9
The guessing is great for interactive work, but can be unsafe when writing programs. It isn’t a problem that it guesses and can produce different types of output when you can see what it creates, but that is not safe deep in the guts of a program.
The function vapply essentially does the same as sapply but without the guessing. You have to tell it what you want as output, and if it cannot produce that, it will give you an error rather than produce output that your program may or may not know what to do with.
241