R语言 编写自定义函数

编程入门 行业动态 更新时间:2024-10-28 16:20:23

R语言 编写<a href=https://www.elefans.com/category/jswz/34/1771438.html style=自定义函数"/>

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语言 编写自定义函数

本文发布于:2023-07-28 19:30:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1288009.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:自定义   函数   语言

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!