apply, lapply, sapply, tapply

apply

> d <- matrix(1:9, ncol=3) > d
     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9
> apply(d, 1, sum) - 행(rows)로 함수 sum을 적용
[1] 12 15 18
> apply(d,2,sum) - 열(columns)로 함수 sum을 적용
[1]  6 15 24

> head(iris,3) - iris 데이터셋의 첫 3번째까지의 행을 관찰
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.1         3.5          1.4         0.2  setosa
2          4.9         3.0          1.4         0.2  setosa
3          4.7         3.2          1.3         0.2  setosa
> apply(iris[,1:4], 2, sum) - iris 데이터셋에서 1~4번째 열을 선택
Sepal.Length  Sepal.Width Petal.Length  Petal.Width 
       876.5        458.6        563.7        179.9 

lapply


> lapply(iris[,1:4], mean)
$Sepal.Length
[1] 5.843333

$Sepal.Width
[1] 3.057333

$Petal.Length
[1] 3.758

$Petal.Width
[1] 1.199333

sapply


> sapply(iris[,1:4], mean)
Sepal.Length  Sepal.Width Petal.Length  Petal.Width 
    5.843333     3.057333     3.758000     1.199333 
> y <- sapply(iris[,1:4], function(x){x > 3})
> head(y,3)
     Sepal.Length Sepal.Width Petal.Length Petal.Width
[1,]         TRUE        TRUE        FALSE       FALSE
[2,]         TRUE       FALSE        FALSE       FALSE
[3,]         TRUE        TRUE        FALSE       FALSE

tapply


> tapply(1:10, rep(1,10), sum)
 1 
55 
> levels(iris$Species)
[1] "setosa"     "versicolor" "virginica" 
> tapply(iris$Sepal.Length, iris$Species, mean)
    setosa versicolor  virginica 
     5.006      5.936      6.588