我很难在数据框和动物园对象之间切换,特别是保持有意义的列名,以及单变量和多变量情况之间的不一致:
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) <- c("Date", "Lepisma saccharina", "Thermobia domestica")
#converting to zoo loses column names in univariate case...
> z1 <- read.zoo(df[,1:2]) #time series for L. saccharina
> colnames(z1)
NULL
> colnames(z1) <- c("Lepisma saccharina") #can't even set column name manually
Error in `colnames<-`(`*tmp*`, value = "Lepisma saccharina") :
attempt to set colnames on object with less than two dimensions
#... but not in multivariate case
> z2 <- read.zoo(df) #time series for both species
> colnames(z2)
[1] "Lepisma saccharina" "Thermobia domestica"
要从动物园对象返回原始格式的数据框,使用它是不够的,as.data.frame
因为它不包含日期列(日期在行名中结束):需要做更多的工作。
zooToDf <- function(z) {
df <- as.data.frame(z)
df$Date <- time(z) #create a Date column
rownames(df) <- NULL #so row names not filled with dates
df <- df[,c(ncol(df), 1:(ncol(df)-1))] #reorder columns so Date first
return(df)
}
这在多变量情况下效果很好,但在单变量情况下显然无法恢复有意义的列名:
> df2b <- zooToDf(z2)
> 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
> df1b <- zooToDf(z1)
> df1b
Date z
1 2012-01-01 4
2 2012-01-02 5
3 2012-01-03 9
4 2012-01-04 7
有没有一种简单的方法来处理单变量和多变量的情况?似乎z1
需要以某种方式记住列名。