函数是一组组合在一起以执行特定任务的语句。 R 语言具有大量内置函数,用户可以创建自己的函数。 在R语言中,函数是一个对象,因此R语言解释器能够将控制传递给函数,以及函数完
函数是一组组合在一起以执行特定任务的语句。 R 语言具有大量内置函数,用户可以创建自己的函数。
在R语言中,函数是一个对象,因此R语言解释器能够将控制传递给函数,以及函数完成动作所需的参数。
该函数依次执行其任务并将控制返回到解释器以及可以存储在其他对象中的任何结果。
使用关键字函数创建 R 语言的函数。 R 语言的函数定义的基本语法如下
function_name <- function(arg_1, arg_2, ...) {
Function body
}
函数的不同部分
内置函数的简单示例是 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 from 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
我们可以在 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)
}
}
# 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语言函数内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!
--结束END--
本文标题: R语言函数基础知识点总结
本文链接: https://www.lsjlt.com/news/123296.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0