# R函数用法图解实例

## 本文概述

1. 编写以执行指定任务。
2. 可能有或没有论点
3. 包含编写我们的代码的主体。
4. 可能会或可能不会返回一个或多个输出值。

“通过使用关键字函数创建R函数。” R函数的语法如下：

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

## 功能类型

### 内建功能

``````# Creating sequence of numbers from 32 to 46.
print(seq(32, 46))

# Finding the mean of numbers from 22 to 80.
print(mean(22:80))

# Finding the sum of numbers from 41 to 70.
print(sum(41:70))``````

### 用户自定义功能

R允许我们在程序中创建自己的函数。用户定义用户定义功能以满足用户需求。一旦创建了这些功能, 我们就可以使用这些功能, 例如内置功能。

``````# Creating a function without an argument.
new.function <- function() {
for(i in 1:5) {
print(i^2)
}
}

new.function()``````

## 带参数的函数调用

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

# Calling the function new.function supplying 10 as an argument.
new.function(10)``````

## 不带参数的函数调用

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

# Calling the function new.function with no argument.
new.function()``````

## 带参数值的函数调用

``````# Creating a function with arguments.
new.function <- function(x, y, z) {
result <- x * y + z
print(result)
}

# Calling the function by position of arguments.
new.function(11, 13, 9)

# Calling the function by names of the arguments.
new.function(x = 2, y = 5, z = 3)``````

## 使用默认参数的函数调用

``````# Creating a function with arguments.
new.function <- function(x = 11, y = 24) {
result <- x * y
print(result)
}

# Calling the function without giving any argument.
new.function()

# Calling the function with giving new values of the argument.
new.function(4, 6)``````

• 回顶