Читать книгу The Big R-Book - Philippe J. S. De Brouwer - Страница 76

Function use for apply()

Оглавление

apply(X, MARGIN, FUN, …) with:

1 X: an array, including a matrix.

2 MARGIN: a vector giving the subscripts which the function will be applied over. E.g., for a matrix ‘1’ indicates rows, ‘2’ indicates columns, ‘c(1, 2)’ indicates rows and columns. Where ‘X’ has named dimnames, it can be a character vector selecting dimension names.

3 FUN: the function to be applied: see ‘Details’. In the case of functions like ‘+’, ‘backquoted or quoted

It is sufficient to provide the data, the dimension of application and the function that has to be applied. To show how this works, we construct a simple example to calculate sums of rows and sums of columns.

cbind()

x <- cbind(x1 = 3, x2 = c(4:1, 2:5)) dimnames(x)[[1]] <- letters[1:8] apply(x, 2, mean, trim = .2) ## x1 x2 ## 3 3 col.sums <- apply(x, 2, sum) row.sums <- apply(x, 1, sum) rbind(cbind(x, Rtot = row.sums), Ctot = c(col.sums, sum(col.sums))) ## x1 x2 Rtot ## a 3 4 7 ## b 3 3 6 ## c 3 2 5 ## d 3 1 4 ## e 3 2 5 ## f 3 3 6 ## g 3 4 7 ## h 3 5 8 ## Ctot 24 24 48

The reader will notice that in the example above the variable x is actually not an array but rather a data frame. The function apply() works however the same: instead of 2 dimensions, there can be more.

apply()

Consider the previous example with the array a, and remember that a has three dimensions: 2 rows, 3 columns, and 2 matrices, then the following should be clear.

# Re-create the array a (shorter code): col.names <- c("col1","col2", "col3") row.names <- c(“R1”,“R2”) matrix.names <- c(“Matrix1”,“Matrix2”) a <- array(c(1,1,10:13),dim = c(2,3,2), dimnames = list(row.names,col.names, matrix.names)) # Demonstrate apply: apply(a, 1, sum) ## R1 R2 ## 46 50 apply(a, 2, sum) ## col1 col2 col3 ## 4 42 50 apply(a, 3, sum) ## Matrix1 Matrix2 ## 48 48

The Big R-Book

Подняться наверх