Using selected vector element as an operator

Viewed 42

If I define a vector as:

vec <- c("for", "paste")

Is there any way to apply a selection on this vector and use the result as an operator? I have tried like this:

vec[1](i, 0:10, print("Hello"))

but the result is an error:

Error: attempt to apply non-function

2 Answers

The first element in 'vec' i.e. for is a Primitive function, so, we can append .Primitive

.Primitive(vec[1])(i, 0:10, print("Hello"))

-output

#[1] "Hello"
#[1] "Hello"
#[1] "Hello"
#[1] "Hello"
#[1] "Hello"
#[1] "Hello"
#[1] "Hello"
#[1] "Hello"
#[1] "Hello"
#[1] "Hello"
#[1] "Hello"

while paste is not Primitive. Not clear from the OP's post about the expected output for second element. With match.fun, we can use

match.fun(vec[2])(rep("Hello", 10), collapse=", ")
#[1] "Hello, Hello, Hello, Hello, Hello, Hello, Hello, Hello, Hello, Hello"

assuming that OP' wants to paste 10 "Hello" into a single string

How about?

vec <- c("for", "paste")
do.call(vec[[1]], list(as.symbol('i'), 0:10, substitute(print('Hello'))))
Related