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)
}

 

原文地址:https://www.cnblogs.com/liujiaxin2018/p/14709604.html