目录

R - 功能( Functions)

函数是组合在一起执行特定任务的一组语句。 R具有大量内置函数,用户可以创建自己的函数。

在R中,函数是一个对象,因此R解释器能够将控制传递给函数,以及函数完成操作可能需要的参数。

该函数依次执行其任务并将控制权返回给解释器以及可能存储在其他对象中的任何结果。

函数定义 (Function Definition)

使用关键字function创建R function 。 R函数定义的基本语法如下 -

function_name <- function(arg_1, arg_2, ...) {
   Function body 
}

功能组件

功能的不同部分是 -

  • Function Name - 这是Function Name的实际名称。 它作为具有此名称的对象存储在R环境中。

  • Arguments - 参数是占位符。 调用函数时,将值传递给参数。 参数是可选的; 也就是说,函数可能不包含任何参数。 参数也可以有默认值。

  • Function Body - 函数体包含一组语句,用于定义函数的功能。

  • Return Value - 函数的返回值是要计算的函数体中的最后一个表达式。

R具有许多in-built函数,可以在程序中直接调用而无需先定义它们。 我们还可以创建和使用我们自己的功能,称为user defined功能。

Built-in Function

内置函数的简单示例是seq()mean()max()sum(x)paste(...)等。它们由用户编写的程序直接调用。 您可以参考最常用的R函数。

# Create a sequence of numbers from 32 to 44.
print(seq(32,44))
# Find mean of numbers from 25 to 82.
print(mean(25:82))
# Find sum of numbers frm 41 to 68.
print(sum(41:68))

当我们执行上面的代码时,它会产生以下结果 -

[1] 32 33 34 35 36 37 38 39 40 41 42 43 44
[1] 53.5
[1] 1526

User-defined Function

我们可以在R中创建用户定义的函数。它们特定于用户想要的内容,一旦创建,就可以像内置函数一样使用它们。 下面是如何创建和使用函数的示例。

# Create a function to print squares of numbers in sequence.
new.function <- function(a) {
   for(i in 1:a) {
      b <- i^2
      print(b)
   }
}	

调用一个函数 (Calling a Function)

# Create a function to print squares of numbers in sequence.
new.function <- function(a) {
   for(i in 1:a) {
      b <- i^2
      print(b)
   }
}
# Call the function new.function supplying 6 as an argument.
new.function(6)

当我们执行上面的代码时,它会产生以下结果 -

[1] 1
[1] 4
[1] 9
[1] 16
[1] 25
[1] 36

在没有参数的情况下调用函数

# Create a function without an argument.
new.function <- function() {
   for(i in 1:5) {
      print(i^2)
   }
}	
# Call the function without supplying an argument.
new.function()

当我们执行上面的代码时,它会产生以下结果 -

[1] 1
[1] 4
[1] 9
[1] 16
[1] 25

使用参数值调用函数(按位置和名称)

函数调用的参数可以按照函数中定义的相同顺序提供,也可以以不同的顺序提供,但可以分配给参数的名称。

# Create a function with arguments.
new.function <- function(a,b,c) {
   result <- a * b + c
   print(result)
}
# Call the function by position of arguments.
new.function(5,3,11)
# Call the function by names of the arguments.
new.function(a = 11, b = 5, c = 3)

当我们执行上面的代码时,它会产生以下结果 -

[1] 26
[1] 58

使用默认参数调用函数

我们可以在函数定义中定义参数的值,并调用函数而不提供任何参数来获取默认结果。 但我们也可以通过提供参数的新值来调用这些函数,并获得非默认结果。

# Create a function with arguments.
new.function <- function(a = 3, b = 6) {
   result <- a * b
   print(result)
}
# Call the function without giving any argument.
new.function()
# Call the function with giving new values of the argument.
new.function(9,5)

当我们执行上面的代码时,它会产生以下结果 -

[1] 18
[1] 45

懒惰的功能评估

对函数的参数进行了懒惰的计算,这意味着只有在函数体需要时才会对它们进行求值。

# Create a function with arguments.
new.function <- function(a, b) {
   print(a^2)
   print(a)
   print(b)
}
# Evaluate the function without supplying one of the arguments.
new.function(6)

当我们执行上面的代码时,它会产生以下结果 -

[1] 36
[1] 6
Error in print(b) : argument "b" is missing, with no default
<上一篇.R - 循环
R - Strings.下一篇>
↑回到顶部↑
WIKI教程 @2018