R编程中的功能

A function in programming is a reusable chunk of code that performs a certain job. For example, if you need to calculate an average of a list of values multiple times, it would be tedious to keep adding code for the operation each time. Instead, you could write a function that calculates the average and call it as many times as you want.

编程中的功能是执行特定工作的可重用代码块。 例如,如果您需要多次计算一个值列表的平均值,那么每次都为该操作添加代码很繁琐。 相反,您可以编写一个函数来计算平均值并根据需要调用多次。

R has hundreds of built-in functions that perform mathematical and graphical operations. R also allows you to define your own customized functions to suit your needs. This tutorial aims to help you with rules in writing and calling functions in R.

R具有数百个执行数学和图形运算的内置函数。 R还允许您定义自己的自定义函数以满足您的需求。 本教程旨在帮助您了解R中编写和调用函数的规则。

R函数的组成部分 (Components of an R Function)

The functions in R can be specified by a function keyword. The following is the syntax for writing functions in R.

R中的功能可以通过function关键字指定。 以下是在R中编写函数的语法。


functionname <- function(argument1, argument2...){
# What you want the function to do
return(returnobject)}
  • The function name here can be any valid R identifier like we discussed earlier.

    这里的函数名称可以是任何有效的R标识符,就像我们之前讨论的那样。
  • Arguments are the values that we wish to pass to the function. A function may or may not take any arguments.

    参数是我们希望传递给函数的值。 一个函数可以接受也可以不接受任何参数。
  • The function manipulates these arguments within its body. The body is the code enclosed between the braces.

    该函数在其体内操纵这些参数。 主体是括号之间的代码。
  • The return statement at the end of the function is used to return the value computed by the function. This can be a numeric value or an object that is created or manipulated within the function body.

    函数末尾的return语句用于返回函数计算的值。 这可以是一个数值,也可以是在函数体内创建或操作的对象。

一个简单的R函数示例 (A simple R function example)

Let’s now write a simple function to understand how this works.

现在让我们编写一个简单的函数来了解其工作原理。


myname <- function(name){
  paste("Hello",name)
} 
name <- readline()
myname(name)

Before we proceed, paste() is a built-in function that concatenates and prints two strings.

在继续之前, paste()是一个内置函数,该函数连接并打印两个字符串。

We have created a function named myname above, which takes a single argument called name. In the function’s body, it prints a message “Hello + name”.

上面我们创建了一个名为myname的函数,该函数接受一个名为name的参数。 在函数的主体中,它会显示一条消息“ Hello + name”。

The name is taken from user input using another built-in function readline(), which can read an entire line with spaces until a newline character is encountered.

该名称是使用另一个内置函数readline()从用户输入中获取的,该函数可以读取带空格的整行,直到遇到换行符为止。

Finally, we are calling the function with the name argument. Let us see how the output goes.

最后,我们使用name参数调用该函数。 让我们看看输出如何。

Output:

输出:


> name <- readline()
Neil Armstrong
> myname(name)
[1] "Hello Neil Armstrong"

After we compile the function block using ctrl + enter, a new section named functions is created in the environment and the function myname is registered there.

使用ctrl + enter编译功能块后,将在环境中创建一个名为functions的新部分,并在其中注册函数myname

As we give the value “Neil Armstrong” to the name variable through our standard input (keyboard), the value gets passed into the function and finally the intended message “Hello Neil Armstrong” is displayed on the console.

当我们通过标准输入(键盘)将名称“ Neil Armstrong”提供给名称变量时,该值将传递到函数中,最后在控制台上显示预期的消息“ Hello Neil Armstrong”。

用返回值编写R函数 (Writing R functions with a return value)

Now let us try out another function and see how the return statement works. Consider a function that takes two numbers, computes the average and returns the average value.

现在让我们尝试另一个函数,看看return语句如何工作。 考虑一个具有两个数字的函数,计算平均值并返回平均值。


average <-function(num1,num2){
  return((num1+num2)/2)
}

This function returns a computed value which can be accessed in the calling statement. The return value is stored in the variable c here.

该函数返回可以在调用语句中访问的计算值。 返回值存储在此处的变量c中。


a=4
b=5
c=average(a,b)
print(c)

Output:

输出:


[1] 4.5

R中的参数处理 (Argument handling in R)

R incorporates lazy evaluation in function handling. This means that expressions are evaluated only when needed.

R在函数处理中合并了惰性评估 。 这意味着仅在需要时才对表达式求值。

R also supports giving default values to arguments.

R还支持为参数提供默认值。


myname2 <- function(name="no name"){
  paste("Hello",name)
}

myname2()

Similar to the above myname function, we have written a myname2 function, but we have a default argument for the name variable with value “no name“. Let us see what happens when we call the function without an argument.

与上面的myname函数类似,我们已经编写了myname2函数,但是我们为name变量使用了一个默认参数,其值为“ no name ”。 让我们看看在不带参数的情况下调用函数会发生什么。


> myname2()
[1] "Hello no name"
> myname2("JournalDev")
[1] "Hello JournalDev"

Without any argument, the function displays the default argument.

不带任何参数的函数将显示默认参数。

R also facilitates checking of missing arguments in functions using missing keyword. This is illustrated using an example below.

R还有助于使用missing关键字检查函数中missing参数。 下面的示例对此进行了说明。

We would like to display a message stating that one of the arguments is missing in the function when only one number is supplied.

我们想显示一条消息,说明仅提供一个数字时函数中缺少一个参数。


#Display an error message when either of the arguments is missing and return #NULL
average <-function(num1,num2){
  if(missing(num1)|missing(num2)){
    print("needs two arguments for average")
    return(NULL)
  }
  return((num1+num2)/2)
}

Now we call average() using a single argument.

现在,我们使用单个参数调用average()


average(2)

Output:

输出:


> average(2)
[1] "needs two arguments for average"
NULL

This will prove a useful feature when writing complex functions further.

当进一步编写复杂函数时,这将被证明是一个有用的功能。

R函数中的可变参数 (Variable Arguments in R Function)

R also allows variable-length arguments list for functions. You can pass arguments without first defining them in the argument list. This is done by using an ellipsis or three dots (...). For example, a function can be defined as follows.

R还允许函数使用变长参数列表。 您可以传递参数而无需先在参数列表中定义它们。 这可以通过使用省略号或三个点( ...) 。 例如,可以如下定义功能。


#Ellipsis represents any number of arguments.
elfunction <-function(...){
  args <- list(...)
  sum <- as.integer(0)
  for(i in 1:length(args)){
    sum=sum+as.integer(args[i]) 
  }
  print(sum)
}

Ignore the structure of for loop for now, just keep in mind that it iterated over the entire length of the arguments list to cumulatively add to the sum value which is initially set to 0. Let us check the output for different cases.

现在暂时忽略for循环的结构,只需记住,它会在参数列表的整个长度上进行迭代,以累积添加到最初设置为0的总和值。让我们检查不同情况下的输出。


> elfunction(1,2,3,4,5)
[1] 15
> elfunction(8,6,24)
[1] 38
> elfunction(1,1,1,1,1,1,1,1,1,1,1,1,1) 
[1] 13

Observe how the elfunction we defined takes any number of arguments without having to define a new one for each. This is a very flexible feature in R.

观察我们定义的elfunction如何接受任意数量的参数,而不必为每个参数定义一个新参数。 这是R中非常灵活的功能。

翻译自: https://www.journaldev.com/34491/functions-in-r-programming

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值