I want to create a scatterplot 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))})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With