自定義函數
R語言實際上是函數的集合,用戶可以使用base,stats等包中的基本函數,也可以編寫自定義函數完成一定的功能
一個函數的結構大致如下所示
myfunction <- function(arglist) {
statements
return(object)
}
其中,myfunction爲函數名稱,arglist爲函數中的參數列表,大括號{}內的語句爲函數體,函數參數是在函數體內部將要處理的值,函數中的對象只在函數內部使用
示例1:
myAdd <- function(x, y) {
return(x+y)
}
a <- myAdd(10000, 456)
a
# 運行結果:
# [1] 10456
示例2:
# 計算標準差
sd2 <- function(x) {
if(!is.numeric(x)) {
stop("the input data must be numeric!\n")
}
if(length(x)==1) {
stop("can not comput sd for one number, a numeric vector required.\n")
}
x2 <- c()
meanx <- mean(x)
for(i in 1:length(x)) {
xn <- x[i] - meanx
x2[i] <- xn^2
}
sum2 <- sum(x2)
sd2 <- sqrt(sum2/(length(x)-1))
return(sd2)
}
sd2(1)
# 運行結果:
# Error in sd2(1) :
# can not comput sd for one number, a numeric vector required.
sd2(c("1", "2"))
# 運行結果:
# Error in sd2(c("1", "2")) : the input data must be numeric!
sd2(c(2, 4, 6, 8, 10))
# 運行結果:
# [1] 3.162278