R语言 编写自定义函数

自定义函数

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值