Jim
Jim

Reputation: 4767

Returning a closure using vapply

If I have a function generator i.e.

prepend_text = function(text) {
  function(x) {
    paste(text, x)
  }
}

Is it possible to use vapply to return a vector of the resulting functions? I do not know how to specify a return type of closure to vapply.

vapply(c('one', 'two', 'three'), FUN.VALUE=???, prepend_text)

Using any other value character(1) ect. yields

# Error in vapply(c('one', 'two', 'three'),  :
#   values must be type 'character',
#  but FUN(X[[1]]) result is type 'closure'

I think this may not be possible, and using sapply actually returns what I want, so this question is largely academic.

The output I am looking for has names for each function as well, so a simple lapply call will not work either.

expected output is equivalent to

c(one=prepend_text('one'), two=prepend_text('two'), three=prepend_text('three'))

Upvotes: 1

Views: 128

Answers (2)

wch
wch

Reputation: 4117

vapply won't return functions, but lapply will. If you want to add names, you can set them on the input object:

x <- c('one', 'two', 'three')
names(x) <- x
lapply(x, prepend_text)

Upvotes: 2

Guillaume
Guillaume

Reputation: 1286

I would recommend to use lapply in those situations.

Can you try this?

lapply(list('one', 'two', 'three'), prepend_text)

Good luck!

Upvotes: 1

Related Questions