This is the default behaviour of [
when used with arrays or data frames; empty dimensions are dropped. Consider
> x[, 2]
[1] 88.74 88.74 86.56 85.82
> class(x[,2])
[1] "numeric"
> is.data.frame(x[,2])
[1] FALSE
In this case the 1-column data frame doesn't need information about which column it is and hence R drops that information and returns the contents of the column as a numeric (in this case) vector, as can be seen above. That vector doesn't have a colname
attribute and hence zoo has nothing to work with.
A solution is to use drop = FALSE
in the index x[, 2, drop = FALSE]
as in
> zx <- zoo(x[, 2, drop = FALSE], as.POSIXct(x$Index, tz="GMT"))
> zx
dbt
2008-08-20 15:03:18 88.74
2008-08-20 15:08:18 88.74
2008-08-20 15:13:18 86.56
2008-08-20 15:18:18 85.82
To see why/how this works, look at
> x[, 2, drop = FALSE]
dbt
1 88.74
2 88.74
3 86.56
4 85.82
> is.data.frame(x[, 2, drop = FALSE])
[1] TRUE
And note the lack of colnames
when the default (TRUE
) is used in the [
index:
> colnames(x[, 2, drop = FALSE])
[1] "dbt"
> colnames(x[, 2, drop = TRUE])
NULL
Now read ?'['
for more details.