R tip: combining multiple lists of vectors into a single list of vectors

So here’s the scenario: you have two lists of vectors that look something like…

list1 = list( c(1,2,3,4,5) , c(1,2,3,4) , c(1,2,3) )
list2 = list( c(6,7,8,9,10), c(5,6,7,8,9,10), c(4,5,6,7,8,9,10) )

…and you’d like to combine them such that you end up with a single list of vectors that look something like…

list3 = list( c(1,2,3,4,5,6,7,8,9,10) , c(1,2,3,4,5,6,7,8,9,10) , c(1,2,3,4,5,6,7,8,9,10) )

Here’s the solution:

> list3 = apply( cbind( list1, list2 ) , 1 , unlist )

R tip: evaluating a text/string as a command

Say we want R to evaluate some text as a command instead of printing it as a string object. For example, when we enter:

> “1:10”

we want it to return a numeric vector:

[1]  1  2  3  4  5  6  7  8  9 10   (instead of: “1:10”)

Unfortunately, there is no native R function that’ll do this for us. So we need to write one ourselves. Happily, it’s pretty straightforward:

> str_eval=function(x) {return(eval(parse(text=x)))}

Once we’ve created this function, we can simply pass it our text (or any string object) and R will evaluate it as if it were simply another R command. Now:

> str_eval(“1:10”)
[1]  1  2  3  4  5  6  7  8  9 10

Success! The only limitation worth noting is that the text that you pass to the str_eval() function must not include quotation marks (“) within its body. Single quotation marks (‘) are okay. So, eval_str(” print(“hi”) “) will break the code, but eval_str(” print(‘hi’) “) will not.

Though of admittedly limited value, this little R trick has gotten me out of more than a couple coding conundrums. Don’t be surprised if one day it helps you find your way around a headache, too.

R Studio: Paul’s tips & tricks

I’ve been using R Studio for quite a while now, and have consequently become pretty familiar (and yes, fond) of this most excellent R IDE. Over that time, I’ve found a handful of super useful tweaks and options that has made working in R Studio a true joy. At this point, if you’re asking yourself, “what the heck is R?” than the rest of this post will probably mean nothing to you; for everyone else, read on! Continue reading

learning R: practical advice

Recently, I’ve had several folks ask me about the best (read: quickest) way to learn R. For those of you fortunate enough to have no idea what I’m talking about, here’s the skinny: R is a statistical programming environment that enables nerds like me to crunch massive amounts of data and produce things like this:


Cool, right? Even better, R is free (as in beer), which means anyone can do this stuff… which brings us back to our topic of the day: What is the quickest way to become an R ninja?
Continue reading