title: R convert between zoo object and data frame, results inconsistent for different numbers of columns?
body: <p>I have difficulty switching between data frames and zoo objects, particularly keeping meaningful column names, and inconsistencies between univariate and multivariate cases: </p>
  
  <pre><code>library(zoo)
  
  #sample data, two species counts over time
  t = as.Date(c("2012-01-01", "2012-01-02", "2012-01-03", "2012-01-04"))
  n1 = c(4, 5, 9, 7)  #counts of Lepisma saccharina
  n2 = c(2, 6, 0, 11) #counts of Thermobia domestica
  df = data.frame(t, n1, n2)
  colnames(df) &lt;- c("Date", "Lepisma saccharina", "Thermobia domestica")
  
  #converting to zoo loses column names in univariate case...
  &gt; z1 &lt;- read.zoo(df[,1:2]) #time series for L. saccharina
  &gt; colnames(z1)
  NULL
  &gt; colnames(z1) &lt;- c("Lepisma saccharina") #can't even set column name manually
  Error in `colnames&lt;-`(`*tmp*`, value = "Lepisma saccharina") : 
    attempt to set colnames on object with less than two dimensions
  #... but not in multivariate case
  &gt; z2 &lt;- read.zoo(df) #time series for both species
  &gt; colnames(z2)
  [1] "Lepisma saccharina"  "Thermobia domestica"
  </code></pre>
  
  <p>To go back from a zoo object to a data frame in the original format, it's not enough to use <code>as.data.frame</code> since it won't include a Date column (the dates end up in the rownames): more work is needed. </p>
  
  <pre><code>zooToDf &lt;- function(z) {
      df &lt;- as.data.frame(z) 
      df$Date &lt;- time(z) #create a Date column
      rownames(df) &lt;- NULL #so row names not filled with dates
      df &lt;- df[,c(ncol(df), 1:(ncol(df)-1))] #reorder columns so Date first
      return(df)
  }
  </code></pre>
  
  <p>This works great on the multivariate case, but clearly can't recover a meaningful column name in the univariate case:</p>
  
  <pre><code>&gt; df2b &lt;- zooToDf(z2)
  &gt; df2b
          Date Lepisma saccharina Thermobia domestica
  1 2012-01-01                  4                   2
  2 2012-01-02                  5                   6
  3 2012-01-03                  9                   0
  4 2012-01-04                  7                  11
  
  &gt; df1b &lt;- zooToDf(z1)
  &gt; df1b
          Date z
  1 2012-01-01 4
  2 2012-01-02 5
  3 2012-01-03 9
  4 2012-01-04 7
  </code></pre>
  
  <p>Is there a simple way to handle <em>both</em> univariate <em>and</em> multivariate cases? It seems <code>z1</code> needs to remember the column name somehow.</p>