J Dud
J Dud

Reputation: 23

Coding a multiline legend with expression containing a comma

I would like to figure out an efficient code to produce a multiline legend in an R plot that pastes within each expression following a comma.

I've tried to use lapply with parse, which doesn't get evaluated.

param_list <- list("None","Omega[0]","R[2]","Omega[0] and R[2]")

value <- list('10', '15', '20', '25')

legend("topleft", legend=lapply(param_list, function(x)
  parse(text=c(paste(param_list[x] ~ ', m = ' ~ value[x], sep='')))))

I would like a legend that reads:

None, m = 10

Omega[0], m = 15

R[2], m = 20

Omega[0] and R[2] = 25

with each of the variables evaluated. Does anyone have any ideas? Explanations of how/why solutions work would also be really appreciated!

Upvotes: 1

Views: 170

Answers (1)

G. Grothendieck
G. Grothendieck

Reputation: 270045

Create both as vectors, paste them together and parse. Put quotes around the comma and and use * and ~ to separate it without and with space from adjacent symbols.

parms <- c("None","Omega[0]","R[2]","Omega[0] ~ and ~ R[2]")
value <- c(10, 15, 20, 25)

plot(0)
legend("topleft", parse(text = paste(parms, "* ',' ~ m == ", value)))

screenshot

Upvotes: 2

Related Questions