Home > other >  How to paste0 in plot in r?
How to paste0 in plot in r?

Time:04-07

With simple data:

set.seed(2015-04-13)
d = data.frame(x =seq(1,10),
           n1 = c(0,0,1,2,3,4,4,5,6,6),
           logp = signif(-log10(runif(10)), 2))>

I can plot

 with(d, I plot(x, n1))

Now for my real data I need to do a for loop using i

 noquote(paste0("n",i))
[1] n1

I tried

i=1
with(d, plot(x, noquote(paste0("n",i))))
Error in xy.coords(x, y, xlabel, ylabel, log) : 

'x' and 'y' lengths differ

Did not work

CodePudding user response:

use get to return the values from the environment of 'd'

with(d, plot(x, get(paste0("n",i)), ylab = paste0('n', i)))

Or extract the column from d

with(d, plot(x, d[[paste0("n", i)]], ylab = paste0('n', i)))

Or convert to symbol and evaluate

with(d, plot(x, eval(as.symbol(paste0('n', i))), ylab = paste0('n', i)))

Note: Both the above notations needs to change the axis labels for 'y'


Or another option is to create a formula with paste

plot(as.formula(paste0('n', i, '~ x')), data = d)
  •  Tags:  
  • r
  • Related