Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...