## With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

No credit card required

# Using apply on a three-dimensional array

1. Create a three-dimensional array:
```> array.3d <- array( seq(100,69), dim = c(4,4,2))
> array.3d

, , 1

[,1] [,2] [,3] [,4]
[1,]  100   96   92   88
[2,]   99   95   91   87
[3,]   98   94   90   86
[4,]   97   93   89   85

, , 2

[,1] [,2] [,3] [,4]
[1,]   84   80   76   72
[2,]   83   79   75   71
[3,]   82   78   74   70
[4,]   81   77   73   69 ```
1. Calculate the sum across the first and second dimensions. We get a one-dimensional array with two elements:
```> apply(array.3d, 3, sum)
[1] 1480 1224

> # verify
> sum(85:100)
[1] 1480 ```
1. Calculate the sum across the third dimension. We get a two-dimensional array:
```> apply(array.3d,c(1,2),sum)
[,1] [,2] [,3] [,4]
[1,]  184  176  168  160
[2,]  182  174  166  158
[3,]  180  172  164  156
[4,]  178  170  162  154 ```

## With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

No credit card required