Nick Vence
Nick Vence

Reputation: 770

Creating a Pure function in R

I'm used to using Pure functions in Mathematica. How might I use them in R? For example:

Given a list of numbers, I want to assign TRUE/FALSE depending on whether the number is positive/negative.

z <- do.call(rnorm,list(n=10))            # Generate 10 numbers
f <- function(x) { x > 0 ? TRUE : FALSE } # Searching for proper syntax
b <- lapply(z,f)

Thanks

Upvotes: 1

Views: 716

Answers (2)

Ben Bolker
Ben Bolker

Reputation: 226182

Narrowly translated, your function would be:

f <- function(x) { if (x > 0)  TRUE else FALSE } 

(you don't need to use ifelse() because this is a context in which x will be a scalar (i.e., a length-1 vector))

f <- function(x) { x > 0 }

would give the same result in your lapply call: so would

lapply(z,">",0)

As commented above you could use ifelse(z>0,TRUE,FALSE). But there's no need to specify logical return values, because the result of z>0 is already a logical vector. The idiomatic way to do this would be

z <- rnorm(10)   ## no need for do.call() in this example
z > 0

(logical comparison is vectorized in R)

Upvotes: 7

Se&#241;or O
Se&#241;or O

Reputation: 17412

Really easy:

b = z > 0

Most simple operations in R are already vectorized.

Upvotes: 5

Related Questions