using apply() to draw multiple lines with abline()

556 views
Skip to first unread message

Bonnie Dixon

unread,
Jun 10, 2014, 6:36:24 PM6/10/14
to davi...@googlegroups.com
Dear D-RUG group mind;

Does anyone know why using an apply() statement to draw multiple lines on a plot with abline() returns "NULL" in addition to drawing the lines?  I am creating a plot in an R Markdown PDF document, and my document would look nicer if it didn't have "NULL" printed along with the plot.  

Here is an example of the problem:

> plot(1)
> x <- cbind(c(0.8, 1.0, 1.2), c(0, 0, 0))
> apply(x, 1, abline)
NULL


Bonnie 

Vince S. Buffalo

unread,
Jun 10, 2014, 6:45:33 PM6/10/14
to davi...@googlegroups.com
Hi Bonnie,

This is because the function abline isn't returning anything each iteration in apply(). apply() needs to return something so it returns NULL. This isn't necessarily a problem; the output can be ignored. If it bothers you, you can use a for loop or capture the output to a variable in local scope:

# maybe something like:
> local(a <-apply(x, 1, abline))
> a # doesn't pollute your environment
Error: object 'a' not found

HTH,
Vince


--
Check out our R resources at http://www.noamross.net/davis-r-users-group.html
---
You received this message because you are subscribed to the Google Groups "Davis R Users' Group" group.
To unsubscribe from this group and stop receiving emails from it, send an email to davis-rug+...@googlegroups.com.
Visit this group at http://groups.google.com/group/davis-rug.
For more options, visit https://groups.google.com/d/optout.



--
Vince Buffalo
Ross-Ibarra Lab (www.rilab.org)
Plant Sciences, UC Davis

Bonnie Dixon

unread,
Jun 10, 2014, 7:24:18 PM6/10/14
to davi...@googlegroups.com
Thanks for the tip, Vince.  I just tried using local(), and that prevented the word NULL from being printed in the console, but it was still printed in my R Markdown document.  So, next I tried doing it as a for loop, and that worked beautifully.  No more "NULL' in my document.  Thanks again!

Bonnie

Vince S. Buffalo

unread,
Jun 10, 2014, 7:29:41 PM6/10/14
to davi...@googlegroups.com
For Rmarkdown/knitr you should be able to set results="hide" in a chunk to not print the results of a calculation too. 

cheers,
Vince

Noam Ross

unread,
Jun 10, 2014, 7:47:19 PM6/10/14
to davi...@googlegroups.com
Alternative the a_ply, l_ply, and d_ply functions in the plyr package are designed for this use. They should return no value.

Bonnie Dixon

unread,
Jun 10, 2014, 7:59:25 PM6/10/14
to davi...@googlegroups.com
I had been assuming that hiding the results would hide the plot too, but I just tried it and, indeed, results="hide" prints the plot, but not the "NULL" result in the document.  That is great to know.

And, thanks, Noam for letting me know about the a_ply, etc. functions in plyr.  That makes it even simpler.

Bonnie
Reply all
Reply to author
Forward
0 new messages