R语言 函数参数

R语言 函数参数

R语言 函数参数

参数是提供给函数的参数,以便在编程语言中执行操作。在R编程中,我们可以使用任意多的参数,并以逗号分隔。在这篇文章中,我们将讨论在R编程中为函数添加参数的不同方法。

R语言 添加参数

我们可以在调用函数时向其传递一个参数,只需在括号内给出数值作为参数。下面是一个带有单个参数的函数的实现。

例子

# Function definition

# To check n is divisible by 5 or not

divisbleBy5 <- function(n){

if(n %% 5 == 0)

{

return("number is divisible by 5")

}

else

{

return("number is not divisible by 5")

}

}

# Function call

divisbleBy5(100)

divisbleBy5(4)

divisbleBy5(20.0)

输出

[1] "number is divisible by 5"

[1] "number is not divisible by 5"

[1] "number is divisible by 5"

R语言 添加多个参数

R编程中的一个函数也可以有多个参数。下面是一个带有多个参数的函数的实现。

例子

# Function definition

# To check a is divisible by b or not

divisible <- function(a, b){

if(a %% b == 0)

{

return(paste(a, "is divisible by", b))

}

else

{

return(paste(a, "is not divisible by", b))

}

}

# Function call

divisible(7, 3)

divisible(36, 6)

divisible(9, 2)

输出

[1] "7 is not divisible by 3"

[1] "36 is divisible by 6"

[1] "9 is not divisible by 2"

在R中添加默认值

函数中的默认值是指在每次调用函数时不需要指定的值。如果该值是由用户传递的,那么用户定义的值就被函数使用,否则就使用默认值。下面是一个带有默认值的函数的实现。

例子

# Function definition to check

# a is divisible by b or not.

# If b is not provided in function call,

# Then divisibility of a is checked with 3 as default

divisible <- function(a, b = 3){

if(a %% b == 0)

{

return(paste(a, "is divisible by", b))

}

else

{

return(paste(a, "is not divisible by", b))

}

}

# Function call

divisible(10, 5)

divisible(12)

输出

[1] "10 is divisible by 5"

[1] "12 is divisible by 3"

点状参数

圆点参数(…)也被称为省略号,它允许函数接受未定义的参数数量。它允许函数接受任意数量的参数。下面是一个带有任意数量参数的函数的例子。

例子

# Function definition of dots operator

fun <- function(n, ...){

l <- list(n, ...)

paste(l, collapse = " ")

}

# Function call

fun(5, 1L, 6i, TRUE, "GeeksForGeeks", "Dots operator")

输出

[1] "5 1 0+6i TRUE GeeksForGeeks Dots operator"

作为参数的函数

在R编程中,函数可以作为参数传递给另一个函数。下面是一个函数作为参数的实现。

例子

# Function definition

# Function is passed as argument

fun <- function(x, fun2){

return(fun2(x))

}

# sum is built-in function

fun(c(1:10), sum)

# mean is built-in function

fun(rnorm(50), mean)

输出

[1] 55

[1] 0.2153183

相关推荐