R語言中自定義函數以及函數的加載


R語言中自定義函數以函數的加載調用

1、自定義函數

test1 <- function(x,y){ a = (x + y) print(a) }
test2 <- function(x, y){ a = x - y print(a) }
test3 <- function(x, y){ a = x * y print(a) }
test4 <- function(x, y){ a = x / y print(a) }

分別保存為4個文件 test1.r、test2.r、test3.r、test4.r。

 

2、函數的加載

dir() source("test1.r") source("test2.r") source("test3.r") source("test4.r")

 

 

 

 

3、函數的調用

(1)、默認位置參數

test1(10,20) (默認情況下是位置參數) test2(10,20) test3(10,20) test4(10,20)

 

 (2)、使用關鍵字參數

test2(x = 10, y = 20) ## 關鍵字參數 test2(x = 20, y = 10)

 

 

(3)、修改test1.r,測試默認參數

test1 <- function(x = 4, y){ a = x + y print(a) }
source("test1.r")

  test1(x = 10, y = 20)     
  test1(y = 20)    ## 不指定x的值時,默認參數 4起作用

 

 

4、批量加載函數

方法1:

remove(list = ls()) dir() r <- dir()[substr(dir(),nchar(dir())-1,nchar(dir())) == ".r"] r for (i in 1:length(r)) { source(r[i]) }

 

 

 

 

方法2:

rm(list = ls()) for (i in dir()) { if (substr(i, nchar(i)-1, nchar(i)) == ".r"){ source(i) } }

 

 

 

 

方法3:

rm(list = ls())
library(stringi)
for (i in dir()) { if(stri_sub(i, -2, -1) == ".r"){ source(i) } }

 

 

方法4:

rm(list = ls()) for (i in list.files(pattern=".r$")) { source(i) }

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM