tluh
tluh

Reputation: 688

R apply - naming the function to be used

Is there a mechanical/stylistic/"other reason" difference between these two functions?

apply(data, 1, fName <- function(x){...})
apply(data, 1, function(x){...})

In this example, they provide the same final output.

dataMod <- c(3, 8, 4, 1, 7, 5, 2, 5)
dataMod <- matrix(dataMod, nrow = 2)
dataMod
#     [,1] [,2] [,3] [,4]
# [1,]    3    4    7    2
# [2,]    8    1    5    5

First apply function:

apply(dataMod, 1, arbitraryName <- function(x){which(x > 3)})
# [[1]]
# [1] 2 3
# 
# [[2]]
# [1] 1 3 4

Second apply function:

apply(dataMod, 1, function(x){which(x > 3)})
# [[1]]
# [1] 2 3
# 
# [[2]]
# [1] 1 3 4

Upvotes: 2

Views: 47

Answers (1)

agenis
agenis

Reputation: 8377

Note the function order is swapped from the question.

In the first case the function is anonymous and exists only temporarily in the call. In this second case, the function is assigned and thus appears in your global environment, and you can reuse it somewhere else.

When you ask to list the objects in the global environment with ls() you get:

apply(dataMod, 1, function(x){which(x > 3)})
ls()
#### [1] dataMod"  
apply(dataMod, 1, arbitraryName <- function(x){which(x > 3)})
ls()
#### [1] "arbitraryName" "dataMod"
arbitraryName(1:5)
#### [1] 4 5

here is a link to Hadley Wickham's page for functional programming, chapter on anonymous functions: link

Anyway, personnally, I try to avoid overloading my environment with single-use objects.

Upvotes: 2

Related Questions