zoukankan      html  css  js  c++  java
  • 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)
    }

     

  • 相关阅读:
    c# 实现鼠标拖拽TreeView节点
    代码生成组合编码
    .net分布式错误,DTC出错问题
    乱七八糟?Ⅱ.哈哈
    用SQL只获取日期的方法
    C#学习之接口
    webservice 上传图片、下载图片
    Python包系列
    多线程多进程模块
    第九章Admin后台系统
  • 原文地址:https://www.cnblogs.com/liujiaxin2018/p/14709604.html
Copyright © 2011-2022 走看看