R Programming  

Week 3 Loop Functions and Debugging 

 

函式(function)

功能

apply(X, MARGIN, 函式, ...)

vector 或array

MARGIN:  1 -->行,MARGIN : 2 -->列,MARGIN: c(1,2) -->行與列(各要素)

 

 
 ( x <- matrix(1:8, ncol=4) )
     [,1] [,2] [,3] [,4]
[1,]    1    3    5    7
[2,]    2    4    6    8
 apply(x, 2, sum)                         # 求各列總値
[1]  3  7 11 15
 apply(x, c(1,2), sqrt)                   # 求各要素平方根
         [,1]     [,2]     [,3]     [,4]
[1,] 1.000000 1.732051 2.236068 2.645751
[2,] 1.414214 2.000000 2.449490 2.828427
各要素加上4:
> apply(x, c(1,2), [x]+4)
Error: unexpected '[' in "apply(x, c(1,2), [" # 找不到所謂的[x]+4 function

> a<-function(x){ # 定義function(x)
x+4                # 為x+4 
} 

> a

function(x){x+4}
> x # 再次確認x值
     [,1] [,2] [,3] [,4]
[1,]    1    3    5    7
[2,]    2    4    6    8
> apply(x, c(1,2), a)  # 將a function代入apply求x+4。 c(1,2)ー>指定行與列中各要素
     [,1] [,2] [,3] [,4]
[1,]    5    7    9   11
[2,]    6    8   10   12

> a<-function(x){x+4} > a function(x){x+4} > x      [,1] [,2] [,3] [,4] [1,]    1    3    5    7 [2,]    2    4    6    8 > apply(x, c(1,2), a)      [,1] [,2] [,3] [,4] [1,]    5    7    9   11 [2,]    6    8   10   12

 

參考資料:

http://cse.naro.affrc.go.jp/takezawa/r-tips/r/24.h...

http://web.ntpu.edu.tw/~cflin/Teach/R/R06EN05Expre...


arrow
arrow

    莎 發表在 痞客邦 留言(0) 人氣()