<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Stochastic Nonsense &#187; Data Munging</title>
	<atom:link href="http://blog.earlh.com/index.php/category/data-munging/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.earlh.com</link>
	<description></description>
	<lastBuildDate>Mon, 19 Sep 2011 03:30:21 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Bash tricks: drop the first line of a file</title>
		<link>http://blog.earlh.com/index.php/2011/07/bash-tricks-drop-the-first-line-of-a-file/</link>
		<comments>http://blog.earlh.com/index.php/2011/07/bash-tricks-drop-the-first-line-of-a-file/#comments</comments>
		<pubDate>Wed, 27 Jul 2011 05:27:22 +0000</pubDate>
		<dc:creator>earl</dc:creator>
				<category><![CDATA[bash]]></category>
		<category><![CDATA[Data Munging]]></category>

		<guid isPermaLink="false">http://blog.earlh.com/?p=711</guid>
		<description><![CDATA[I work with a bunch of data that often comes in text files. I regularly want to cut off the header / first line, but I thought that to use tail you had to know how many lines are in &#8230; <a href="http://blog.earlh.com/index.php/2011/07/bash-tricks-drop-the-first-line-of-a-file/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I work with a bunch of data that often comes in text files.  I regularly want to cut off the header / first line, but I thought that to use tail you had to know how many lines are in your file.  It turns out that if you just use</p>
<pre class="brush:bash">
$ tail -n +2 [file]
</pre>
<p>it will just skip the first line without forcing you to know how many lines there are.  </p>
<pre class="brush:bash;">
earl $ cat a.csv
1
2
3
4
earl $ tail -n +2 a.csv
2
3
4
</pre>
<p>This is much more convenient for piping into awk or other commands downstream.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.earlh.com/index.php/2011/07/bash-tricks-drop-the-first-line-of-a-file/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Saving output of a command and echoing to the screen</title>
		<link>http://blog.earlh.com/index.php/2011/07/saving-output-of-a-command-and-echoing-to-the-screen/</link>
		<comments>http://blog.earlh.com/index.php/2011/07/saving-output-of-a-command-and-echoing-to-the-screen/#comments</comments>
		<pubDate>Tue, 19 Jul 2011 20:33:20 +0000</pubDate>
		<dc:creator>earl</dc:creator>
				<category><![CDATA[bash]]></category>
		<category><![CDATA[Data Munging]]></category>

		<guid isPermaLink="false">http://blog.earlh.com/?p=699</guid>
		<description><![CDATA[When using bash, it&#8217;s really nice to both save the output of a command to a file and print it on the screen. I couldn&#8217;t find something that did this so I wrote my own ruby script. A utility that &#8230; <a href="http://blog.earlh.com/index.php/2011/07/saving-output-of-a-command-and-echoing-to-the-screen/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>When using bash, it&#8217;s really nice to both save the output of a command to a file and print it on the screen.  I couldn&#8217;t find something that did this so I wrote my own ruby script.  A utility that does exactly what you want is actually included in a standard linux install, but with a filename that I simply couldn&#8217;t google.  tee does what you need:</p>
<pre class="brush:bash;">
$ hadoop --jar $J/job.jar --job asdf | tee -a log.asdf.00
</pre>
<p>saves stdout to log.job.00 and echoes to screen</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.earlh.com/index.php/2011/07/saving-output-of-a-command-and-echoing-to-the-screen/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Horizontal Paging of Greenplum or Postgres Queries</title>
		<link>http://blog.earlh.com/index.php/2010/01/horizontal-paging-of-greenplum-or-postgres-queries/</link>
		<comments>http://blog.earlh.com/index.php/2010/01/horizontal-paging-of-greenplum-or-postgres-queries/#comments</comments>
		<pubDate>Wed, 27 Jan 2010 00:58:56 +0000</pubDate>
		<dc:creator>earl</dc:creator>
				<category><![CDATA[Data Munging]]></category>
		<category><![CDATA[greenplum]]></category>
		<category><![CDATA[postgres]]></category>

		<guid isPermaLink="false">http://blog.earlh.com/?p=558</guid>
		<description><![CDATA[When using gpsql or pgsql to query greenplum or postgres respectively, query results which exceed the width of your term will wrap in a very annoying fashion. To get horizontal paging, set the environmental variable PAGER: export PAGER='less -RSFX' then &#8230; <a href="http://blog.earlh.com/index.php/2010/01/horizontal-paging-of-greenplum-or-postgres-queries/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>When using gpsql or pgsql to query greenplum or postgres respectively, query results which exceed the width of your term will wrap in a very annoying fashion.  To get horizontal paging, set the environmental variable PAGER:</p>
<pre class='brush:bash;'>
export PAGER='less -RSFX'
</pre>
<p>then either in your psql or gpsql session, or in your .psqlrc file,</p>
<pre class='brush:bash;'>
\pset pager always
</pre>
<p>Note that if you just want the pager for long output, not wide, you can omit the always from the pset command.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.earlh.com/index.php/2010/01/horizontal-paging-of-greenplum-or-postgres-queries/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Interactive Plotting in R</title>
		<link>http://blog.earlh.com/index.php/2010/01/interactive-plotting-in-r/</link>
		<comments>http://blog.earlh.com/index.php/2010/01/interactive-plotting-in-r/#comments</comments>
		<pubDate>Mon, 25 Jan 2010 21:53:34 +0000</pubDate>
		<dc:creator>earl</dc:creator>
				<category><![CDATA[Data Munging]]></category>
		<category><![CDATA[Plotting]]></category>
		<category><![CDATA[R]]></category>
		<category><![CDATA[R Tip]]></category>
		<category><![CDATA[Visualization]]></category>

		<guid isPermaLink="false">http://blog.earlh.com/?p=538</guid>
		<description><![CDATA[There are many ways to compare univariate distributions; one of my favorites is violin plots. However, if you are only comparing two distributions, then the best solution is often a scatter plot. To that end, I&#8217;ve build some code that &#8230; <a href="http://blog.earlh.com/index.php/2010/01/interactive-plotting-in-r/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>There are many ways to compare univariate distributions; one of my favorites is <a href="http://blog.earlh.com/index.php/2009/07/visualizing-and-comparing-distributions-part-8-of-a-series/">violin plots</a>.  However, if you are only comparing two distributions, then the best solution is often a scatter plot.  To that end, I&#8217;ve build some code that creates an interactive scatter plot of two distributions and allows you to interactively print arbitrary strings on the graph when you select / deselect points.  This creates a slightly kludgy but very handy tool for hand comparing distributions.</p>
<p>Unfortunately, truly interactive plotting isn&#8217;t really a part of R and you are thus forced to lean on external tools.  I picked JGR, the java gui for R.  This is best used by getting the <a href="http://jgr.markushelbig.org/Download.html">JGR launch tool</a>.</p>
<p>Basically, I have data with multiple tests; a single line shows the results for one item across several tests.  I wish to compare the distributions.</p>
<pre class="brush:text;">
> head(age)
    name    default      test1      test2
1 item 1 0.02110710 0.01900870 0.02030870
2 item 2 0.03160770 0.02926650 0.03345660
3 item 3 0.03909570 0.03702500 0.04016650
4 item 4 0.00262195 0.00225917 0.00302822
5 item 5 0.01668860 0.01555010 0.01783400
6 item 6 0.04223370 0.03904630 0.04123270
</pre>
<p><a href='http://blog.earlh.com/wp-content/uploads/2010/01/iplot.test_.csv_.txt'>test data</a></p>
<p>You can use this function to throw up a window, and allow you to draw a box around items to see their information displayed in the upper left.</p>
<pre class="brush:text;">
  library('iplots')

  visCompare <- function(dat, xname, yname){  

    # override this to display your preferred text
    makeDispString <- function(row){
      sprintf('%s : %s = %0.3f; %s = %0.3f; diff = %0.3f', row$name,
        xname, row[[xname]], yname, row[[yname]], row[[xname]] - row[[yname]])
    }

    ypoint <- 0.05 + max(dat[[yname]])

    iplot(x=dat[[xname]], y=dat[[yname]], xlab=xname, ylab=yname,
      ylim=c(0, ypoint + 0.05), xlim=c(0, max(dat[[xname]])), lwd=2)

    iabline(coef=c(0,1))
    d <- iplot.data()
    cat('Select break from the menu to exit loop')

    txtObj <- NULL

    while (!is.null(ievent.wait())){
      if (iset.sel.changed()){
        cat("sel changed\n")
        s <- iset.selected()

        if (length(s) >= 1){
          if (!is.null(txtObj) ){
            iobj.rm( txtObj )
          }

          aa <- paste( makeDispString(dat[s[1:min(3, length(s))],]), collapse="\n")
          cat(paste(aa, "\n"))
          txtObj <- itext(x=0, y=ypoint, labels=aa)
        }

      } else {
        if ( !is.null(txtObj)){

          cat(paste('removing ', txtObj, "\n"))
          iobj.rm( txtObj )
          txtObj <- NULL
        }
      }

    }
  }
</pre>
<p>To test, you can use these two bits of code:</p>
<pre class="brush:text;">
if (F){
	read.csv(file='iplot.test.csv.txt', header=T, sep=',')
	visCompare(age, 'default', 'test2')
}
if (F){
	read.csv(file='iplot.test.csv.txt', header=T, sep=',')
	myDispFn <- function(a){ return(paste(a$name, 'blah blah', sep=' : ') }
	visCompare(age, 'default', 'test2', myDispFn)
}
</pre>
<p>And here are the results: first, a visual check via scatterplot of the differences of the two distributions:<br />
<a href="http://blog.earlh.com/wp-content/uploads/2010/01/JGR01.png"><img src="http://blog.earlh.com/wp-content/uploads/2010/01/JGR01-300x236.png" alt="" title="JGR01 -- scatterplot of two distributions" width="300" height="236" class="aligncenter size-medium wp-image-550" /></a></p>
<p>and with the ability to highlight points and see what you're looking at:<br />
<a href="http://blog.earlh.com/wp-content/uploads/2010/01/JGR02.png"><img src="http://blog.earlh.com/wp-content/uploads/2010/01/JGR02-300x237.png" alt="" title="JGR -- scatterplot with info for item" width="300" height="237" class="aligncenter size-medium wp-image-551" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.earlh.com/index.php/2010/01/interactive-plotting-in-r/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Querying Postgres or Greenplum From R on a Mac, Installation Instructions</title>
		<link>http://blog.earlh.com/index.php/2010/01/querying-postgres-or-greenplum-from-r-on-a-mac-installation-instructions/</link>
		<comments>http://blog.earlh.com/index.php/2010/01/querying-postgres-or-greenplum-from-r-on-a-mac-installation-instructions/#comments</comments>
		<pubDate>Thu, 21 Jan 2010 21:19:28 +0000</pubDate>
		<dc:creator>earl</dc:creator>
				<category><![CDATA[Data Munging]]></category>
		<category><![CDATA[R]]></category>
		<category><![CDATA[R Tip]]></category>
		<category><![CDATA[greenplum]]></category>
		<category><![CDATA[postgres]]></category>
		<category><![CDATA[R and Databases]]></category>

		<guid isPermaLink="false">http://blog.earlh.com/?p=530</guid>
		<description><![CDATA[NB: this works on 64b versions of R; I tested it with the R64 app with R version 2.10.1 on Snow Leopard Step by step instructions for talking to Postgres or Greenplum: install macports install postgres; I used 8.4 sudo &#8230; <a href="http://blog.earlh.com/index.php/2010/01/querying-postgres-or-greenplum-from-r-on-a-mac-installation-instructions/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>NB: this works on 64b versions of R; I tested it with the R64 app with R version 2.10.1 on Snow Leopard</p>
<p>Step by step instructions for talking to Postgres or Greenplum:</p>
<ol>
<li> install <a href="http://www.macports.org/">macports</a></li>
<li> install postgres; I used 8.4<br />
<code>
<pre class="brush:bash;">
sudo port install postgresql84
</pre>
<p></code>
</li>
<li> in a shell, create an environmental variable PG_CONFIG pointing to the pg_config binary installed by postgres.  In my installation, this is something like<br />
<code>
<pre class="brush:bash;">
export PG_CONFIG=/opt/local/lib/postgresql84/bin/pg_config
</pre>
<p></code>
</li>
<li> in the same shell, tell R to install the RPostgreSQL package *from source*, ie<br />
<code>
<pre class="brush:text;">
$ R
> install.packages('RPostgreSQL', type='source')
</pre>
<p></code>
</li>
<li>test the installation works:<br />
<code>
<pre class="brush:text;">
> library('RPostgreSQL')
Loading required package: DBI
> drv <- dbDriver('PostgreSQL')
> db <- dbConnect(drv, host='greenplum.ip', user='earl', dbname='dbname')
> dbGetQuery(db, 'select 1')
?column?
1       1
</pre>
<p></code>
</li>
</ol>
<p>Diagnosing error messages / problems:</p>
<ul>
<li>If R says<br />
<code>
<pre class="brush:text;">
Warning message:
In install.packages("RPostgreSQL") : package ‘RPostgreSQL’ is not available
</pre>
<p></code><br />
you must specify to install the package from source, as above with type=&#8217;source&#8217; </li>
<li>If you get compilation errors when installing the package that mention libpq-fe.h, then R <a href="http://blog.earlh.com/index.php/2009/12/querying-postgres-or-greenplum-from-r-on-a-mac/">can&#8217;t find pg_config</a></li>
<li>if the package installs but when loading it you get errors involving <a href="http://blog.earlh.com/index.php/2010/01/querying-databases-from-r-on-a-mac/">missing symbol _PQbackendPID</a> then you are mixing 32 and 64 bit software.</li>
</ul>
<p>Follow the links for instructions to fix your problems.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.earlh.com/index.php/2010/01/querying-postgres-or-greenplum-from-r-on-a-mac-installation-instructions/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Querying Databases From R on a Mac</title>
		<link>http://blog.earlh.com/index.php/2010/01/querying-databases-from-r-on-a-mac/</link>
		<comments>http://blog.earlh.com/index.php/2010/01/querying-databases-from-r-on-a-mac/#comments</comments>
		<pubDate>Tue, 12 Jan 2010 00:28:08 +0000</pubDate>
		<dc:creator>earl</dc:creator>
				<category><![CDATA[Data Munging]]></category>
		<category><![CDATA[R]]></category>
		<category><![CDATA[R Tip]]></category>
		<category><![CDATA[greenplum]]></category>
		<category><![CDATA[postgres]]></category>
		<category><![CDATA[R and Databases]]></category>
		<category><![CDATA[R Tips]]></category>

		<guid isPermaLink="false">http://blog.earlh.com/?p=520</guid>
		<description><![CDATA[I use a mac, currently running OS 10.6 / Snow Leopard, and I&#8217;d like to query our greenplum / postgres database from R. This used to work with R 2.9, but I unfortunately had to upgrade R, and R 2.10 &#8230; <a href="http://blog.earlh.com/index.php/2010/01/querying-databases-from-r-on-a-mac/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I use a mac, currently running OS 10.6 / Snow Leopard, and I&#8217;d like to query our greenplum / postgres database from R.  This used to work with R 2.9, but I unfortunately had to upgrade R, and R 2.10 on the mac is a 64 bit app.  So, I want to use either RODBC or RPostgreSQL packages under 64 bit R on a mac to query postgres / greenplum.</p>
<p>First, I tried just <a href="http://blog.earlh.com/index.php/2009/12/querying-postgres-or-greenplum-from-r-on-a-mac/">installing RPostgreSQL</a> as before.  Unfortunately, I started getting weird errors when I attempted to load the package:</p>
<p><code>
<pre  class="brush:text;">
>library('RPostgreSQL')
Loading required package: DBI
Error in dyn.load(file, DLLpath = DLLpath, ...) :
  unable to load shared library '/Library/Frameworks/R.framework/Resources/library/RPostgreSQL/libs/x86_64/RPostgreSQL.so':
  dlopen(/Library/Frameworks/R.framework/Resources/library/RPostgreSQL/libs/x86_64/RPostgreSQL.so, 6): Symbol not found: _PQbackendPID
  Referenced from: /Library/Frameworks/R.framework/Resources/library/RPostgreSQL/libs/x86_64/RPostgreSQL.so
  Expected in: flat namespace
 in /Library/Frameworks/R.framework/Resources/library/RPostgreSQL/libs/x86_64/RPostgreSQL.so
Error: package/namespace load failed for 'RPostgreSQL'
</pre>
<p></code></p>
<p>The key bit of the error message is the missing symbol: _PQbackendPID.  Some googling suggested this could be caused by mixing 32 and 64 bit libs.  I used file to check and yes, indeed, I had a 32 bit version of Postgres that was refusing to talk to a 64 bit version on R.  Suck.</p>
<p>In brief, the solution is to use ports to install postgres &#8212; in this case, postgres 8.4 as such:<br />
<code>
<pre class="brush:bash;">
sudo port install postgres84
</pre>
<p></code></p>
<p>you can use the file command to see what architecture your installed postgres is configured as:<br />
<code>
<pre  class="brush:bash;">
laptop:src earl$ file `echo $PG_CONFIG`
/opt/local/lib/postgresql84/bin/pg_config: Mach-O 64-bit executable x86_64
</pre>
<p></code></p>
<p>checking, my previous postgres 8.4 install, from the Postgres Plus prebuild package, produces<br />
<code>
<pre  class="brush:bash;">
file /Library/PostgresPlus/8.4SS/bin/pg_config
/Library/PostgresPlus/8.4SS/bin/pg_config: Mach-O universal binary with 2 architectures
/Library/PostgresPlus/8.4SS/bin/pg_config (for architecture ppc):	Mach-O executable ppc
/Library/PostgresPlus/8.4SS/bin/pg_config (for architecture i386):	Mach-O executable i386
</pre>
<p></code><br />
Notice the lack of any 64bit support.</p>
<p>Then open a terminal, set the PG_CONFIG environmental variable to point to the right location, then run R from the terminal and install the package.<br />
<code>
<pre class="brush:text;">
laptop: work earl$ export PG_CONFIG=/opt/local/lib/postgresql84/bin/pg_config

laptop: work earl$ R64
install.packages('RPostgreSQL', type='source')
</pre>
<p></code></p>
<p>If you have misconfigured the pg_config, this is the relevant bit of the compilation error message you will receive:<br />
<code>
<pre class="brush:text;">
checking for "/libpq-fe.h"... no
configure: error: File libpq-fe.h not in ; installation may be broken.
ERROR: configuration failed for package ‘RPostgreSQL’
* removing ‘/Library/Frameworks/R.framework/Versions/2.10/Resources/library/RPostgreSQL’
</code></pre>
<p>Otherwise, RPostgreSQL will compile and install.  Seriously, though, there *must* be a better way of distributing software on macs.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.earlh.com/index.php/2010/01/querying-databases-from-r-on-a-mac/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Querying Postgres or Greenplum from R on a Mac</title>
		<link>http://blog.earlh.com/index.php/2009/12/querying-postgres-or-greenplum-from-r-on-a-mac/</link>
		<comments>http://blog.earlh.com/index.php/2009/12/querying-postgres-or-greenplum-from-r-on-a-mac/#comments</comments>
		<pubDate>Thu, 31 Dec 2009 16:00:50 +0000</pubDate>
		<dc:creator>earl</dc:creator>
				<category><![CDATA[Data Munging]]></category>
		<category><![CDATA[R]]></category>
		<category><![CDATA[R Tip]]></category>
		<category><![CDATA[greenplum]]></category>
		<category><![CDATA[postgres]]></category>
		<category><![CDATA[R and Databases]]></category>
		<category><![CDATA[R Tips]]></category>

		<guid isPermaLink="false">http://blog.earlh.com/?p=501</guid>
		<description><![CDATA[So, I&#8217;m using snow leopard, and I want to query our postgres / greenplum database. First things first: I&#8217;m familiar with the RODBC package on CRAN. This installs fine, since it&#8217;s a binary package. I also installed the ODBC Administrator &#8230; <a href="http://blog.earlh.com/index.php/2009/12/querying-postgres-or-greenplum-from-r-on-a-mac/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>So, I&#8217;m using snow leopard, and I want to query our postgres / greenplum database.</p>
<p>First things first: I&#8217;m familiar with the <a href="http://cran.r-project.org/web/packages/RODBC/index.html">RODBC</a> package on CRAN.  This installs fine, since it&#8217;s a binary package.  I also installed the ODBC Administrator app that you have to download from apple <a href="http://support.apple.com/downloads/ODBC_Administrator_Tool_for_Mac_OS_X"> here </a>.  Now all I need is the postgres ODBC driver, which is harder to get your hands on than you&#8217;d think.  I first installed postgres84 via ports, but that didn&#8217;t seem to include the ODBC driver.  I then installed the full postgres84 package in a pre-packaged distro from <a href="http://www.enterprisedb.com/products/pgdownload.do#osx"> EnterpriseDB</a>.  This required rebooting my mac and then manually disabling postgres db &#8212; since I only want the odbc drivers &#8212; by removing the obvious files from /Library/LaunchDaemons.  Then&#8230; no love.  I started ODBC Administrator, selected a System DSN, chose the psqlODBC driver, and then ended up with a screen that had no prompts and just a bunch of key / value pairs with no suggestions as to what might be required &#8212; typically some variation of host, hostname, user, username, etc.  Unfortunately, clicking on the key field in the rows doesn&#8217;t allow me to edit them;  Hitting enter allows me to modify the key, but hell if I know how to modify the value.</p>
<p>So my next attempt was installing the <a href="http://cran.r-project.org/web/packages/RPostgreSQL/index.html">RPostgreSQL</a> package from CRAN.<br />
<code>
<pre class="brush:text;">
install.packages('RPostgreSQL')
</pre>
<p></code><br />
fails, as by default R will only grab binary packages and this is a source package.  You will have to do this:<br />
<code>
<pre class="brush:text;">
install.packages('RPostgreSQL', type='source')
</pre>
<p></code></p>
<p>This, of course, then fails to build, complaining that it can&#8217;t find libpq-fe.h.  Awesome.</p>
<p>If you look hard enough, the missing header file should be wherever you installed postgres.  Either in /opt/local/something if you used ports to install postgres, or in /Library/PostgresPlus/8.4SS if you installed the binary distribution as I did.  Inside that directory lives an include directory which has our .h file.  Setting PG_INCDIR to that path &#8212; eg<br />
<code>
<pre class="brush:bash;">
export PG_INCDIR="/Library/PostgresPlus/8.4SS/include"
</pre>
<p></code></p>
<p>then running R from that shell now gets me far enough that when you rerun install.packages from R you get a complaint about a missing lib:<br />
<code>
<pre class="brush:text;">
> install.packages('RPostgreSQL')
--- Please select a CRAN mirror for use in this session ---
Loading Tcl/Tk interface ... done
Warning message:
In getDependencies(pkgs, dependencies, available, lib) :
  package ‘RPostgreSQL’ is not available
> ? install.packages
> install.packages('RPostgreSQL', type='source')
also installing the dependency ‘DBI’

trying URL 'http://cran.stat.ucla.edu/src/contrib/DBI_0.2-5.tar.gz'
Content type 'application/x-tar' length 308395 bytes (301 Kb)
opened URL
==================================================
downloaded 301 Kb

trying URL 'http://cran.stat.ucla.edu/src/contrib/RPostgreSQL_0.1-6.tar.gz'
Content type 'application/x-tar' length 141399 bytes (138 Kb)
opened URL
==================================================
downloaded 138 Kb

* Installing *source* package ‘DBI’ ...
** R
** inst
** preparing package for lazy loading
Creating a new generic function for "summary" in "DBI"
** help
*** installing help indices
 >>> Building/Updating help pages for package 'DBI'
     Formats: text html latex example
  DBI-internal                      text    html    latex
  DBIConnection-class               text    html    latex   example
  DBIDriver-class                   text    html    latex   example
  DBIObject-class                   text    html    latex   example
  DBIResult-class                   text    html    latex   example
  dbCallProc                        text    html    latex
  dbCommit                          text    html    latex   example
  dbConnect                         text    html    latex   example
  dbDataType                        text    html    latex   example
  dbDriver                          text    html    latex   example
  dbGetInfo                         text    html    latex   example
  dbListTables                      text    html    latex   example
  dbReadTable                       text    html    latex   example
  dbSendQuery                       text    html    latex   example
  dbSetDataMappings                 text    html    latex   example
  fetch                             text    html    latex   example
  make.db.names                     text    html    latex   example
  print.list.pairs                  text    html    latex   example
** building package indices ...
* DONE (DBI)
* Installing *source* package ‘RPostgreSQL’ ...
checking for gcc... gcc
checking for C compiler default output file name... a.out
checking whether the C compiler works... yes
checking whether we are cross compiling... no
checking for suffix of executables...
checking for suffix of object files... o
checking whether we are using the GNU C compiler... yes
checking whether gcc accepts -g... yes
checking for gcc option to accept ISO C89... none needed
checking for pg_config... no
configure: checking for PostgreSQL header files
checking for "/Library/PostgresPlus/8.4SS/include/libpq-fe.h"... yes
configure: creating ./config.status
config.status: creating src/Makevars
** libs
** arch - i386
gcc -arch i386 -std=gnu99 -I/Library/Frameworks/R.framework/Resources/include -I/Library/Frameworks/R.framework/Resources/include/i386 -I/Library/PostgresPlus/8.4SS/include -I/usr/local/include    -fPIC  -g -O2 -c RS-DBI.c -o RS-DBI.o
gcc -arch i386 -std=gnu99 -I/Library/Frameworks/R.framework/Resources/include -I/Library/Frameworks/R.framework/Resources/include/i386 -I/Library/PostgresPlus/8.4SS/include -I/usr/local/include    -fPIC  -g -O2 -c RS-PostgreSQL.c -o RS-PostgreSQL.o
gcc -arch i386 -std=gnu99 -dynamiclib -Wl,-headerpad_max_install_names -mmacosx-version-min=10.4 -undefined dynamic_lookup -single_module -multiply_defined suppress -L/usr/local/lib -o RPostgreSQL.so RS-DBI.o RS-PostgreSQL.o -L -lpq -F/Library/Frameworks/R.framework/.. -framework R -Wl,-framework -Wl,CoreFoundation
ld: library not found for -lpq
collect2: ld returned 1 exit status
make: *** [RPostgreSQL.so] Error 1
ERROR: compilation failed for package ‘RPostgreSQL’
* Removing ‘/Library/Frameworks/R.framework/Versions/2.9/Resources/library/RPostgreSQL’

The downloaded packages are in
	‘/private/var/folders/-E/-E9MDL2qECqW8Ik4CfUX6U+++TM/-Tmp-/RtmpvTtehd/downloaded_packages’
Updating HTML index of packages in '.Library'
Warning message:
In install.packages("RPostgreSQL", type = "source") :
  installation of package 'RPostgreSQL' had non-zero exit status
</pre>
<p></code></p>
<p>Thanks to an email to the <a href="http://www.mail-archive.com/r-help@r-project.org/msg67209.html">R help list</a>, the answer is to tell gcc where to find pg_config, which somehow magically solves this.  eg:<br />
<code>
<pre class="brush:text;">
earl:bin $ export PG_CONFIG=/Library/PostgresPlus/8.4SS/bin/pg_config
earl:bin $ R

R version 2.9.2 (2009-08-24)
[...]
> install.packages('RPostgreSQL', type='source')
--- Please select a CRAN mirror for use in this session ---
[...]
checking for pg_config... /Library/PostgresPlus/8.4SS/bin/pg_config
checking for "/Library/PostgresPlus/8.4SS/include/libpq-fe.h"... yes
configure: creating ./config.status
config.status: creating src/Makevars
** libs
** arch - i386
gcc -arch i386 -std=gnu99 -I/Library/Frameworks/R.framework/Resources/include -I/Library/Frameworks/R.framework/Resources/include/i386 -I/Library/PostgresPlus/8.4SS/include -I/usr/local/include    -fPIC  -g -O2 -c RS-DBI.c -o RS-DBI.o
gcc -arch i386 -std=gnu99 -I/Library/Frameworks/R.framework/Resources/include -I/Library/Frameworks/R.framework/Resources/include/i386 -I/Library/PostgresPlus/8.4SS/include -I/usr/local/include    -fPIC  -g -O2 -c RS-PostgreSQL.c -o RS-PostgreSQL.o
gcc -arch i386 -std=gnu99 -dynamiclib -Wl,-headerpad_max_install_names -mmacosx-version-min=10.4 -undefined dynamic_lookup -single_module -multiply_defined suppress -L/usr/local/lib -o RPostgreSQL.so RS-DBI.o RS-PostgreSQL.o -L/Library/PostgresPlus/8.4SS/lib -lpq -F/Library/Frameworks/R.framework/.. -framework R -Wl,-framework -Wl,CoreFoundation
** R
** inst
** preparing package for lazy loading
Creating a new generic function for "format" in "RPostgreSQL"
Creating a new generic function for "print" in "RPostgreSQL"
** help
*** installing help indices
 >>> Building/Updating help pages for package 'RPostgreSQL'
     Formats: text html latex example
  PostgreSQL                        text    html    latex   example
  PostgreSQLConnection-class        text    html    latex   example
  PostgreSQLDriver-class            text    html    latex   example
  PostgreSQLObject-class            text    html    latex   example
  PostgreSQLResult-class            text    html    latex   example
  S4R                               text    html    latex   example
  dbApply-methods                   text    html    latex   example
  dbApply                           text    html    latex   example
  dbBuildTableDefinition            text    html    latex
  dbCallProc-methods                text    html    latex
  dbCommit-methods                  text    html    latex   example
  dbConnect-methods                 text    html    latex   example
  dbDataType-methods                text    html    latex   example
  dbDriver-methods                  text    html    latex   example
  dbGetInfo-methods                 text    html    latex   example
  dbListTables-methods              text    html    latex   example
  dbObjectId-class                  text    html    latex   example
  dbReadTable-methods               text    html    latex   example
  dbSendQuery-methods               text    html    latex   example
  dbSetDataMappings-methods         text    html    latex   example
  fetch-methods                     text    html    latex   example
  isIdCurrent                       text    html    latex   example
  make.db.names-methods             text    html    latex   example
  postgresqlDBApply                 text    html    latex   example
  postgresqlSupport                 text    html    latex
  safe.write                        text    html    latex   example
  summary-methods                   text    html    latex
** building package indices ...
* DONE (RPostgreSQL)

The downloaded packages are in
	‘/private/var/folders/-E/-E9MDL2qECqW8Ik4CfUX6U+++TM/-Tmp-/RtmpurzqTb/downloaded_packages’
Updating HTML index of packages in '.Library'
> library(RPostgreSQL)
Loading required package: DBI
</pre>
<p></code></p>
<p>You can now test this:<br />
<code>
<pre class="brush:text;">
> library('RPostgreSQL')
Loading required package: DBI
> drv <- dbDriver('PostgreSQL')
> drv
 PostgreSQLDriver:(1825)
> db <- dbConnect(drv, host='greenplum.ip', user='earl', dbname='db01')
> db
 PostgreSQLConnection:(1825,0)
> dbGetQuery(db, 'select 1')
  ?column?
1        1
>
>
>
> dbGetQuery(db, 'select count(*) from earl_fav_wd')
  count
1    34
>
</pre>
<p></code></p>
<p>Success!  I can query my greenplum db from R.  Also, I hate computers.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.earlh.com/index.php/2009/12/querying-postgres-or-greenplum-from-r-on-a-mac/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Querying Databases in R</title>
		<link>http://blog.earlh.com/index.php/2009/08/querying-databases-in-r/</link>
		<comments>http://blog.earlh.com/index.php/2009/08/querying-databases-in-r/#comments</comments>
		<pubDate>Fri, 14 Aug 2009 16:00:36 +0000</pubDate>
		<dc:creator>earl</dc:creator>
				<category><![CDATA[Data Munging]]></category>
		<category><![CDATA[R]]></category>
		<category><![CDATA[R Tip]]></category>
		<category><![CDATA[data frame]]></category>
		<category><![CDATA[greenplum]]></category>
		<category><![CDATA[mysql]]></category>
		<category><![CDATA[postgres]]></category>
		<category><![CDATA[R and Databases]]></category>
		<category><![CDATA[R Tips]]></category>

		<guid isPermaLink="false">http://blog.earlh.com/?p=449</guid>
		<description><![CDATA[One of the first things you&#8217;ll want to do in R is set it up to talk to databases. The easiest way to do this is using ODBC, via package RODBC. To get the package, run > install.packages(RODBC) Once you &#8230; <a href="http://blog.earlh.com/index.php/2009/08/querying-databases-in-r/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>One of the first things you&#8217;ll want to do in R is set it up to talk to databases.  The easiest way to do this is using ODBC, via package RODBC.</p>
<p>To get the package, run<br />
<code>
<pre class="brush:text;">
> install.packages(RODBC)
</pre>
<p></code></p>
<p>Once you have RODBC installed, you call it in R as follows.  But it&#8217;s very simple: a bit of setup, then sqlQuery will run your sql and return the results in a data frame.<br />
<code>
<pre class="brush: text;">
library(RODBC)

db <- odbcConnect( dsn='your dsn name' )
sql <- 'select page_id, count(*) as cnt
           from document_ads
           group by page_id
           having count(*) > 1'

results <- sqlQuery(db, sql, errors=T, rows_at_time=1024)
str(results)
'data.frame':	282432 obs. of  2 variables:
 $ page_id: int  17646774 17115332 17606022 15899428 17099174 17283774 8604200 16315025 17259751 17283270 ...
 $ cnt            : int  489 1119 132 113 148 200 112 121 1135 633 ...
</pre>
<p></code></p>
<p>On Windows, you setup the DSNs in the ODBC Data Sources inside the control panel; on MacOS, mysql includes a program called ODBC Administrator; on linux, you'll have to install <a href="http://www.easysoft.com/developer/interfaces/odbc/linux.html"> unixODBC </a>.</p>
<p>Also, it's often convenient to write code that caches your query results, particularly if the query takes a while.  I've found that the easiest thing to do is write the results into a data file and check for the file existence like such:<br />
<code>
<pre class="brush:text;">
filename <- 'query cache.RData'
if (!file.exists(filename)){
   # don't have a cached copy so run the query
   library(RODBC)
   [snip]
   query1 <- sqlQuery(db, sql, errors=T, rows_at_time=1024)

   # save the query results for the future
   save(list=c('query1', 'sql'), file=filename)
   rm(list=c('query1', 'sql') )
}
load(file=filename)
</pre>
<p></code</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.earlh.com/index.php/2009/08/querying-databases-in-r/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>MySQL, Batch Imports, and Rails</title>
		<link>http://blog.earlh.com/index.php/2009/08/mysql-batch-imports-and-rails/</link>
		<comments>http://blog.earlh.com/index.php/2009/08/mysql-batch-imports-and-rails/#comments</comments>
		<pubDate>Thu, 13 Aug 2009 13:00:48 +0000</pubDate>
		<dc:creator>earl</dc:creator>
				<category><![CDATA[Data Munging]]></category>
		<category><![CDATA[mysql]]></category>

		<guid isPermaLink="false">http://blog.earlh.com/?p=426</guid>
		<description><![CDATA[I really love Rails, but it&#8217;s not the most performant code in the world. Though it doesn&#8217;t often arise in CRUD programming, if you do any sort of stats, ML, or data analytics, you&#8217;ll frequently find yourself wanting to import &#8230; <a href="http://blog.earlh.com/index.php/2009/08/mysql-batch-imports-and-rails/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I really love Rails, but it&#8217;s not the most performant code in the world.  Though it doesn&#8217;t often arise in CRUD programming, if you do any sort of stats, ML, or data analytics, you&#8217;ll frequently find yourself wanting to import lots of data into your db.  You could create an ActiveRecord object for each row, but this is glacial, requiring one round trip to the db server per row, and is likely to abuse the kindness of your dba.  Instead, there is a wonderful gem called ar-extensions that allows you to access mysql&#8217;s native bulk import facilities.  To use it you just call Model.import with arrays of data and their corresponding fields.  For example, say I have a table like this:</p>
<p><code>
<pre class="brush:sql;">
mysql> describe adsense_analytics_days;
+------------------+----------+------+-----+---------+----------------+
| Field            | Type     | Null | Key | Default | Extra          |
+------------------+----------+------+-----+---------+----------------+
| id               | int(11)  | NO   | PRI | NULL    | auto_increment |
| page_id          | int(11)  | NO   | MUL | NULL    |                |
| impressions      | int(11)  | YES  |     | NULL    |                |
| clicked          | int(11)  | YES  |     | NULL    |                |
| ecpm             | float    | YES  |     | NULL    |                |
| ctr              | float    | YES  |     | NULL    |                |
| cpc              | float    | YES  |     | NULL    |                |
| revenue          | float    | YES  |     | NULL    |                |
| start_date       | date     | YES  | MUL | NULL    |                |
| end_date         | date     | YES  |     | NULL    |                |
| created_at       | datetime | YES  |     | NULL    |                |
+------------------+----------+------+-----+---------+----------------+
11 rows in set (0.09 sec)

mysql> 
</pre>
<p></code><br />
This has a corresponding model AdsenseAnalyticsDay.  Batch importing with rails is then trivial:</p>
<p><code>
<pre class="brush: ruby;">
require 'ar-extensions'
require 'ar-extensions/import/mysql'

# instead of
if false
  rows.each do |row|
    AdsenseAnalyticsDay.create( ) # etc
  end
end

# you can accomplish a bulk import from, eg, a csv as such:
f = File.new('bulk_import.csv', 'r')
data = []
while line = f.gets
  puts "#{line}" if rand(1000) >= 999
  # pid, impr, clicked, ecpm, ctr, cpc, revenue, start_date, end_date, created_at
  d = line.split(',')
  (0..2).each{ |i| d[i] = d[i].to_i  }
  (3..6).each{ |i| d[i] = d[i].to_f }
  data << d[0..8]
end
f.close

fields = [:page_id, :impressions, :clicked, :ecpm, :ctr, :cpc, :revenue, :start_date, :end_date]
AdsenseAnalyticsDay.import(fields, data, {:validate => false })
</pre>
<p></code></p>
<p>where the csv looks like:<br />
<code>
<pre class="brush: bash;">
MacBook-2:work earl$ head bulk_import.csv
0,344,5,0.755814,0.0145349,0.052,0.26,2009-08-06,2009-08-06,2009-08-10 19:49:12
1,8,1,0,0.125,0,0,2009-08-06,2009-08-06,2009-08-10 19:49:12
2,32,9,76.875,0.28125,0.273333,2.46,2009-08-06,2009-08-06,2009-08-10 19:49:12
4,16,1,1.875,0.0625,0.03,0.03,2009-08-06,2009-08-06,2009-08-10 19:49:12
6,17,2,8.82353,0.117647,0.075,0.15,2009-08-06,2009-08-06,2009-08-10 19:49:12
12,15,1,80,0.0666667,1.2,1.2,2009-08-06,2009-08-06,2009-08-10 19:49:12
34,5,0,0,0,0,0,2009-08-06,2009-08-06,2009-08-10 19:49:12
36,2,0,0,0,0,0,2009-08-06,2009-08-06,2009-08-10 19:49:12
39,46,2,11.7391,0.0434783,0.27,0.54,2009-08-06,2009-08-06,2009-08-10 19:49:12
41,3,0,0,0,0,0,2009-08-06,2009-08-06,2009-08-10 19:49:12
MacBook-2:work earl$ 
</pre>
<p></code></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.earlh.com/index.php/2009/08/mysql-batch-imports-and-rails/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Examining Data Frames &#8212; head and tail</title>
		<link>http://blog.earlh.com/index.php/2009/08/examining-data-frames-head-and-tail/</link>
		<comments>http://blog.earlh.com/index.php/2009/08/examining-data-frames-head-and-tail/#comments</comments>
		<pubDate>Sun, 02 Aug 2009 07:30:39 +0000</pubDate>
		<dc:creator>earl</dc:creator>
				<category><![CDATA[Data Munging]]></category>
		<category><![CDATA[R]]></category>
		<category><![CDATA[R Tip]]></category>
		<category><![CDATA[data frame]]></category>

		<guid isPermaLink="false">http://blog.earlh.com/?p=367</guid>
		<description><![CDATA[head and tail, for those familiar with the unix command line, are two very handy utilities for looking at data frames. Along with str, which displays the structure of a data frame, they help you look at your data: > &#8230; <a href="http://blog.earlh.com/index.php/2009/08/examining-data-frames-head-and-tail/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>head and tail, for those familiar with the unix command line, are two very handy utilities for looking at data frames.  Along with str, which displays the structure of a data frame, they help you look at your data:</p>
<p><code>
<pre class="brush:text;">
> d <- data.frame(mean=rep(1:10,5), val = rnorm(n=50, mean=rep(1:10,5)))
> d <- d[ order(d$mean), ]
>
> str(d)
'data.frame':	50 obs. of  2 variables:
 $ mean: int  1 1 1 1 1 2 2 2 2 2 ...
 $ val : num  2.303 2.222 -1.153 1.795 -0.232 ...
>
> head(d)
   mean        val
1     1  2.3026422
11    1  2.2216371
21    1 -1.1533163
31    1  1.7945563
41    1 -0.2318763
2     2 -0.4994239
>
> tail(d)
   mean       val
49    9  8.462525
10   10 10.437314
20   10 10.815264
30   10 10.218853
40   10  9.754245
50   10  9.596825
>
</pre>
<p></code> </p>
<p>If you are familiar with data frames, you&#8217;ll know that head(d) is no different than displaying the first 6 rows via subsetting, eg, d[1:6, ] but it saves some typing.  tail, on the other hand, saves us from either asking first how many rows a data frame has with nrow, or typing a mess: d[ (nrow(d)-5):nrow(d), ]<br />
<code>
<pre class="brush:text;">
> nrow(d)
[1] 50
> d[45:50,]
   mean       val
49    9  8.462525
10   10 10.437314
20   10 10.815264
30   10 10.218853
40   10  9.754245
50   10  9.596825
> d[ (nrow(d)-5):nrow(d), ]
   mean       val
49    9  8.462525
10   10 10.437314
20   10 10.815264
30   10 10.218853
40   10  9.754245
50   10  9.596825
>
</pre>
<p></brush></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.earlh.com/index.php/2009/08/examining-data-frames-head-and-tail/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

