使用R中的sprintf评估动态表达式

时间:2012-08-03 08:06:18

标签: r printf

我正在尝试在评估之前以下列方式动态创建表达式:

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

我想得到以下字符串:

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

,然后可以使用eval()进行评估。

我尝试过:sprintf(exp1,authors),但这不起作用......解决方案是什么?

1 个答案:

答案 0 :(得分:4)

您可以使用:

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

或没有图书馆:

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