Why hadn’t I written a function for that?

I’m often typing the same bits of code over and over. Those bits of code really should be made into functions.

For example, I’m still using base graphics. (ggplot2 is on my “to do” list, really!) Often some things will be drawn with a slight overlap of the border of the plotting region. And in heatmaps with image, the border is often obscured. I want a nice black rectangle around the outside.

So I’ll write the following:

u <- par("usr")
rect(u[1], u[3], u[2], u[4])

I don’t know how many times I’ve typed that! Today I realized that I should put those two lines in a function add_border(). And then I added add_border() to my R/broman package.

It was a bit more work adding the Roxygen2 comments for the documentation, but now I’ve got a proper function that is easier to use and much more clear.

Update: @tpoi pointed out that box() does the same thing as my add_border(). My general point still stands, and this raises the additional point: twitter + blog → education.

I want to add, “I’m an idiot” but I think I’ll just say that there’s always more that I can learn about R. And I’ll remove add_border from R/broman and just use box().


Tags: , ,

7 Responses to “Why hadn’t I written a function for that?”

  1. anspiess Says:

    Hi Karl,

    had a look in your Github files.
    I like your runningmean.c for fast averaging. However, I think you could speed it up considerably if you take the testing for method (i.e if(method==1 || method==2 || method==4)) out of the loops so you don’t test for the same 10000 times on a vector of 100000 and window size 10…


  2. D Holmes Says:

    Perhaps we can start a real thread with the best simple functions: I use the construct c(“A”,”B”,”C”) everywhere, which involves a lot of matching quotes. Now, I use s(“A;B;C”) where s<-function(x,sep=";") { unlist(strsplit(x,sep)) }
    Saves only 4 bytes, but it's much easier to read and to type.

  3. Rich Huang Says:

    Making a snippet for your R code editor is another alternative to creating a function for a simple task.

    • Karl Broman Says:

      A reasonable idea, but I still prefer to write a function, preferably within a package. Then you can make the idea available to others, and your code may be made more readable.

  4. mmkstarr Says:

    Reblogged this on mmkstarr pages and commented:
    Because self-doubt cripples functional thought.

Comments are closed.