Tuesday, September 25, 2012

How to read in a vector stored as a R expression in a text file (and other things)

A Facebook friend asked:

R question: I have a file that contains a list of entries of the format "c(2.34306542445513, 1.07370083005978e-06)". How can I coax R to read such entries literally? In other words, I want to make an object from the entries. pars <- c(2.34306542445513, 1.07370083005978e-06)

My first response was to do this the hard way. Let's say we have a text file with one or multiple rows as described:



Before realizing that there is a much easier way, I pointed out that we can do what's been proposed using readLines, strsplit, paste, and as.numeric. I include this primarily to emphasize how easy it :



Anyway, shortly after posting this I realized that this could be done much more easily using the functions eval and parse:



That's it!

P.S. please let me know if you prefer this new "text box" format for R code and session results, or my previous method of font only based demarcation (e.g., shown here, and in almost any other post on this blog).

7 comments:

  1. The "other things" was supposed to be that we can obviously use eval & parse to evaluate other expressions stored as strings or in a text file as well. How to do this depends on the case, but should be fairly obvious. We can also combine these with strsplit to pull out specific expressions from a longer string.

    ReplyDelete
  2. Hey Liam,
    One limitation of the text box format is that, unlike figures and the old font-based R code, it doesn't render properly in a feed reader (at least for Google Reader in Chrome, not sure if it's generally the case).
    Keep up the good work!
    Travis

    ReplyDelete
  3. Ugghh. How bad does it render? Can you send me a screen shot? Thanks for the feedback. Liam

    ReplyDelete
    Replies
    1. The line breaks aren't translating, so each block of code turns into a single big 'paragraph'. I'm emailing a screenshot.
      T

      Delete
    2. I have now switched to creating a CSS div class for code in the blog HTML, and then using that. How does it look? (E.g., here.)

      Delete
  4. It doesn't render too well in Chrome for iPad, either, because it uses a non-monospaced font.

    ReplyDelete
  5. @Travis and Roger - thanks for the feedback!

    ReplyDelete