if statement on arrays in R

In a simple way of stating my problem, consider I have the following function:

> ff<-function(a){ if (a>0){ return ("positive") } else{ return("negative") } }

now:

> ff(-1)
[1] "negative"
> ff(1)
[1] "positive"

while when use an array:

> print(ff(c(-1,1)))
[1] "negative" "negative"
Warning message:
In if (a > 0) { :
  the condition has length > 1 and only the first element will be used

I was expecting

print(ff(c(-1,1)))=("negative" "positive")

How should I solve this?

Upvotes: 0

Views: 1864

Answers (3)

lmo
lmo

Reputation: 38510

You could also use symnum or cut. You just have to define the proper cut points.

symnum(elements, c(-Inf, 0, Inf), c("negative", "positive"))
negative positive positive negative

cut(elements, c(-Inf, 0, Inf), c("negative", "positive"))
[1] negative positive positive negative
Levels: negative positive

Note: Using elements vector from oriol-mirosa's answer:

elements <- c(-1, 1, 1, -1)

As an exciting aside, symnum will work with matrices as well:

# convert elements vector to a matrix
elementsMat <- matrix(elements, 2, 2)
symnum(elementsMat, c(-Inf, 0, Inf), c("negative", "positive"))

[1,] negative positive
[2,] positive negative

Upvotes: 0

Aramis7d
Aramis7d

Reputation: 2496

Alternately, check out the dplyr function for more reliable behavior.

a <- c(-1, 1, 1, -1)

if_else(a < 0, "negative", "positive", "missing")

which gives:

[1] "negative" "positive" "positive" "negative"

Upvotes: 2

Oriol Mirosa
Oriol Mirosa

Reputation: 2826

Your function is not vectorized, so it's not going to work as you expect. You should use ifelse instead, which is vectorized:

elements <- c(-1, 1, 1, -1)

ff <- function(a) {
  ifelse(a > 0, 'Positive', 'Negative')  
}

ff(elements)

[1] "Negative" "Positive" "Positive" "Negative"

Upvotes: 5

Related Questions