单列对象的zoo列名

ery*_*ery 5 r zoo

我对动物园中的列名有疑问.我通常从数据框创建zoo对象,然后从数据框中选择列作为zoo列.我发现,如果我只为zoo对象指定一列,那么动物园将不会使用列名.这是否意味着它不被视为动物园中的"专栏"?

以下是我通常使用一列和两列的示例.

Lines.1 = "Index,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"

Lines.2 = "Index,dbt,rh
2008-08-20 15:03:18,88.74,18.25
2008-08-20 15:08:18,88.74,17.25
2008-08-20 15:13:18,86.56,18.75
2008-08-20 15:18:18,85.82,19.75"

x =read.table(text = Lines.1, header = TRUE, sep = ",")
y =read.table(text = Lines.2, header = TRUE, sep = ",")

colnames(x)
colnames(y)

library(zoo)
zx = zoo(x[,2], as.POSIXct(x$Index, tz="GMT"))
zy = zoo(y[,2:3], as.POSIXct(y$Index, tz="GMT"))

colnames(zx)
colnames(zy)
Run Code Online (Sandbox Code Playgroud)

结果如下:

> colnames(zx)
NULL
> colnames(zy)
[1] "dbt" "rh" 
Run Code Online (Sandbox Code Playgroud)

我错过了什么吗?

Sve*_*ein 7

这种行为不是由于zoo.x[,2]不返回数据框而是向量.因此,没有列,也没有列名.

x[,2]
[1] 88.74 88.74 86.56 85.82
Run Code Online (Sandbox Code Playgroud)

如果要返回单列数据框,可以x[2]不使用逗号或x[,2, drop = FALSE].

x[2]
    dbt
1 88.74
2 88.74
3 86.56
4 85.82

x[,2, drop = FALSE]
    dbt
1 88.74
2 88.74
3 86.56
4 85.82
Run Code Online (Sandbox Code Playgroud)

默认值dropTRUE.这意味着单列数据帧会自动转换为向量.

现在,它有效:

zx <- zoo(x[2], as.POSIXct(x$Index, tz="GMT"))
colnames(zx)
[1] "dbt"
Run Code Online (Sandbox Code Playgroud)


Rei*_*son 6

这是[与数组或数据框一起使用时的默认行为; 空尺寸被删除.考虑

> x[, 2]
[1] 88.74 88.74 86.56 85.82
> class(x[,2])
[1] "numeric"
> is.data.frame(x[,2])
[1] FALSE
Run Code Online (Sandbox Code Playgroud)

在这种情况下的1列数据帧不需要关于它是柱,并因此ř下降的信息,并返回列作为数值的内容(在这种情况下)向量作为从上面可以看出的信息.该向量没有colname属性,因此动物园无法使用.

解决方案是drop = FALSE在索引x[, 2, drop = FALSE]中使用

> 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
Run Code Online (Sandbox Code Playgroud)

要了解其原因和方法,请查看

> 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
Run Code Online (Sandbox Code Playgroud)

并注意缺少在索引中使用colnamesdefault(TRUE)的时间[:

> colnames(x[, 2, drop = FALSE])
[1] "dbt"
> colnames(x[, 2, drop = TRUE])
NULL
Run Code Online (Sandbox Code Playgroud)

现在阅读?'['更多细节.