How to use conditional statement and return value for a function in R?

孤街醉人 提交于 2019-12-14 03:31:42

问题


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?

Thanks


回答1:


ans <- function(x){
  ifelse(x < 0, 2*abs(x), x)
}

will do.

> ans(2)
[1] 2

> ans(-2)
[1] 4

Explanation: We can use the built-in base R function ifelse(). The logic is pretty simple:

ifelse(condition, output if condition is TRUE, output if condition is FALSE)

Therefore, ifelse(x < 0, 2*abs(x), x) will do the following:

  1. evaluate whether value x is negative (<0)
  2. if TRUE, return 2*abs(x)
  3. if FALSE, return x

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.

Comparison:

ans_if <- function(x){
  if(x < 0){2*abs(x)}else{x}
}

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)

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

whereas the if() variant will throw a warning

> 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

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.



来源:https://stackoverflow.com/questions/54825426/how-to-use-conditional-statement-and-return-value-for-a-function-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!