d.b
d.b

Reputation: 32548

Use character string as options for plotting

Say I have the different options for plotting saved as a character. For the sake of this question, let's assume I have received tons of these from elsewhere.

option1 = "type = 'p', col = 'red', pch = 19, cex = 2"
option2 = "type = 'l', lty = 2, lwd = 2, col = 'blue'"

I suppose I'd have to parse them and identify the different options. But before I do that I was wondering if there is a way to use them directly when plotting.

Here is a code that doesn't work.

#Data
set.seed(42)
x = rnorm(20)
y = rnorm(20)

plot(x, y, option1)
plot(x, y, option2)

Upvotes: 1

Views: 170

Answers (2)

Tonio Liebrand
Tonio Liebrand

Reputation: 17699

How about this:

eval(parse(text = paste0("plot(x, y, ", option1, ")")))
eval(parse(text = paste0("plot(x, y, ", option2, ")")))

Upvotes: 3

Spacedman
Spacedman

Reputation: 94237

You could construct the plotting call as a string and evaluate its parsed form:

eval(parse(text = paste0("plot(x,y,",option1,")")))

Upvotes: 2

Related Questions