R apply - naming the function to be used -


is there mechanical/stylistic/"other reason" difference between these 2 functions?

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

in example, provide 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 

note function order swapped question.

in first case function anonymous , exists temporarily in call. in second case, function assigned , appears in global environment, , can reuse somewhere else.

when ask list objects in global environment ls() 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 link hadley wickham's page functional programming, chapter on anonymous functions: link

anyway, personnally, try avoid overloading environment single-use objects.


Comments