R语言 编写自定义函数
生活随笔
收集整理的這篇文章主要介紹了
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语言 编写自定义函数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 安装ps显示无法连接到adobe服务器,
- 下一篇: python金融趋势指标计算:布林带