自定义函数"/>
R语言 编写自定义函数
自定义函数
R语言实际上是函数的集合,用户可以使用base,stats等包中的基本函数,也可以编写自定义函数完成一定的功能
一个函数的结构大致如下所示
myfunction <- function(arglist) {statementsreturn(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] - meanxx2[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
更多推荐
R语言 编写自定义函数
发布评论