nassimhddd
nassimhddd

Reputation: 8510

Evaluate a dynamic expression with sprintf in R

I'm trying to create a expression dynamically before its evaluation in the following way:

authors <- c("John1","John2")
exp1 <- "(Author1==%s & Author2==%s)"

I would like to get the following string:

desired_output <- "(Author1==\"John1\" & Author2!=\"John2\")"

, that can then be evaluated with eval().

I have tried: sprintf(exp1,authors) , but that doesn't work... what is the solution ?

Upvotes: 2

Views: 1004

Answers (1)

MvG
MvG

Reputation: 60858

You can use this:

library(plyr)
splat(sprintf)(c(exp1, authors))

Or without a library:

do.call(sprintf,as.list(c(exp1,authors)))

Upvotes: 4

Related Questions