开发者

"abline" doesn't work after "plot" when inside "with"

I want to create a scatterplot开发者_如何学C and draw the regression line for a subset of a dataset. To give a reproducible example I'll use the CO2 dataset.

I tried this but the regression line doesn't appear for some reason

with(subset(CO2,Type=="Quebec"),plot(conc,uptake),abline(lm(uptake~conc)))

What is the correct way to give a command like this? Can I do it with a one-liner?


You need to provide both your lines of code as a single R expression. The abline() is being taken as a subsequent argument to with(), which is the ... argument. This is documented a a means to pass arguments on to future methods, but the end result is that it is effectively a black hole for this part of your code.

Two options, i) keep one line but wrap the expression in { and } and separate the two expressions with ;:

with(subset(CO2,Type=="Quebec"), {plot(conc,uptake); abline(lm(uptake~conc))})

Or spread the expression out over two lines, still wrapped in { and }:

with(subset(CO2,Type=="Quebec"), 
     {plot(conc,uptake)
      abline(lm(uptake~conc))})

Edit: To be honest, if you are doing things like this you are missing out on the advantages of doing the subsetting via R's model formulae. I would have done this as follows:

plot(uptake ~ conc, data = CO2, subset = Type == "Quebec")
abline(lm(uptake ~ conc, data = CO2, subset = Type == "Quebec"), col = "red")

The with() is just causing you to obfuscate your code with braces and ;.


From ?with: with ... evaluates expr in a local environment created using data. You're passing abline() via .... You need to do something like this:

with(subset(CO2,Type=="Quebec"),{plot(conc,uptake);abline(lm(uptake~conc))})


Gavin and Joshua offer good solutions to your immediate problem; here's the equivalent plot using ggplot:

library(ggplot2)
qplot(conc, uptake, data = CO2[CO2$Type == "Quebec" , ]) + stat_smooth(method = "lm", se = FALSE)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜