Dan
Dan

Reputation: 12074

Default name of object passed to function by apply in R

Say I have the following code:

# Create data frame
df <- data.frame(a = 1:5, b = 6:10)

#   a  b
# 1 1  6
# 2 2  7
# 3 3  8
# 4 4  9
# 5 5 10

Now, I print each row individually using apply

apply(df, MARGIN = 1, print)

If I wanted to reference a particular element of each row passed to FUN in apply, I'd do it by defining an anonymous function, like this:

apply(df, MARGIN = 1, function(x)print(x[1]))

This code just prints the first element in each row.

In the tidyverse, an object passed to a function via a pipe is by default referred to by .. If this was also the case for apply, I could write something along the lines of...

apply(df, MARGIN = 1, print(.[1]))

My question: can I refer to the object passed to FUN by a default name thus avoiding the need for a function definition (e.g., function(x))?

Upvotes: 0

Views: 50

Answers (1)

G. Grothendieck
G. Grothendieck

Reputation: 269694

1) restructure data We can write:

apply(df[1], 1, print)

2) gsubfn One can also use fn$ in gsubfn. In that case we can specify functions using formula notation. The free variables, here just x, are assumed to be the arguments of the function.

library(gsubfn)
fn$apply(df, 1, ~ print(x[1]))

3) magrittr We can also do this:

library(magrittr)
df %>% apply(1, . %>% `[`(1) %>% print)

or

df %>% apply(1, . %>% extract(1) %>% print)

or

df %>% apply(1, . %>% { print(.[1]) } )

although you have to be careful in the case of the last one since the brace brackets are absolutely needed and the following does not work since it seems it interprets the second dot as df rather than the input to the anonymous function.

library(magrittr)
df %>% apply(1, . %>% print(.[1])) # wrong

Upvotes: 2

Related Questions