如何在R中为函数使用条件语句和返回值? [英] How to use conditional statement and return value for a function in R?
问题描述
我必须创建一个函数:ans(x),它返回值 2*abs(x),如果 x 是负数,否则为 x 值.我可以使用什么命令?
I have to create a function as: ans(x) which returns the value 2*abs(x), if x is negative, and the value x otherwise. What command could i use?
谢谢
推荐答案
ans <- function(x){
ifelse(x < 0, 2*abs(x), x)
}
会做的.
> ans(2)
[1] 2
> ans(-2)
[1] 4
说明:我们可以使用内置的基本 R
函数 ifelse()
.逻辑很简单:
Explanation:
We can use the built-in base R
function ifelse()
. The logic is pretty simple:
ifelse(条件,条件为真时输出,条件为假时输出)
因此,ifelse(x <0, 2*abs(x), x)
将执行以下操作:
Therefore, ifelse(x < 0, 2*abs(x), x)
will do the following:
- 评估值 x 是否为负 (<0)
- 如果
TRUE
,返回2*abs(x)
- 如果
FALSE
,返回x
- evaluate whether value x is negative (<0)
- if
TRUE
, return2*abs(x)
- if
FALSE
, returnx
ifelse()
相对于传统的 if()
的优势在于向量化.if()
只能处理单个值,ifelse()
将评估作为输入给出的任何向量.
The advantage of ifelse()
over traditional if()
is the vectorization. if()
can only handle a single value, ifelse()
will evaluate any vector given as input.
对比:
ans_if <- function(x){
if(x < 0){2*abs(x)}else{x}
}
这是同一个函数,使用传统的 if()
结构.将单个值作为输入将导致两个函数的输出相同:
This is the same function, using a traditional if()
structure. Giving a single value as input will result in the same output for both functions:
> ans(-2)
[1] 4
> ans_if(-2)
[1] 4
但是如果你想输入多个值,比方说
But if you want to input multiple values, let's say
test <- c(-1, -2, 3, -4)
ifelse()
变体将评估向量的每个元素并生成正确的输出作为相同长度的向量:
the ifelse()
variant will evaluate every element of the vector and generate the correct output as a vector of the same length:
> ans(test)
[1] 2 4 3 8
而 if()
变体会抛出警告
> ans_if(test)
[1] 2 4 6 8
Warning message:
In if (x < 0) { :
the condition has length > 1 and only the first element will be used
并返回错误的输出,因为只有第一个值用于评估 (-1) 并且对整个向量的操作基于此评估.
and return the wrong output, as only the first value was used for evaluation (-1) and the operation over the whole vector was based on this evaluation.
这篇关于如何在R中为函数使用条件语句和返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!