2

我有一个动物园时间序列,称为merged

merged <- structure(c("53736", "53736", "53737", "53737", "53738", "53738", 
"2353.96", "2377.84", "2388.4", "2397.52", "2432.62", "2407.52", 
"68.1", "71.4", "68.2", "75.3", "107.5", "80.3", "10.6", "11.1", 
"10.6", "11.7", "16.8", "12.5", "2006-01-01 11:17:00", "2006-01-01 23:15:00", 
"2006-01-02 11:17:00", "2006-01-02 23:15:00", "2006-01-03 11:16:00", 
"2006-01-03 23:17:00", "11.206564", "13.019471", "11.784637", 
"14.039267", "18.505121", "15.057849"), .Dim = c(6L, 6L), .Dimnames = list(
    NULL, c("station_id", "ztd", "zwd", "iwv", "timestamp", "pwc"
    )), index = structure(c(1136113200, 1136156400, 1136199600, 
1136242800, 1136286000, 1136329200), class = c("POSIXct", "POSIXt"
)), class = "zoo")

查看结构,我们可以看到它有许多列:

> str(merged)
‘zoo’ series from 2006-01-01 11:00:00 to 2010-03-24 23:00:00
  Data: chr [1:2966, 1:6] "53736" "53736" "53737" "53737" "53738" "53738" "53739" ...
 - attr(*, "dimnames")=List of 2
  ..$ : NULL
  ..$ : chr [1:6] "station_id" "ztd" "zwd" "iwv" ...
  Index:  POSIXct[1:2966], format: "2006-01-01 11:00:00" "2006-01-01 23:00:00" "2006-01-02 11:00:00" ...

但是,如果我尝试在其他一些列上使用数学运算符创建一个新列,则它不起作用:

> merged$error <- merged$pwc - merged$iwv
Error in `-.default`(merged$pwc, merged$iwv) : 
  non-numeric argument to binary operator

我确定我以前做过这个并且它有效,所以我无法弄清楚我做错了什么。有没有人有任何想法?

4

1 回答 1

6

正如评论中提到的:您的数据是字符,而不是数字,并且-没有为字符向量定义。它们都是字符的原因是因为该timestamp列以及 zoo 对象是具有索引属性的矩阵这一事实(并且您不能在矩阵中混合类型)。

因此,您需要将相关列转换merged为数字。

merged2 <- merged[,!grepl("timestamp",colnames(merged))]
merged2 <- zoo(apply(merged2,2,type.convert), index(merged))
merged2$error <- merged2$pwc - merged2$iwv
于 2012-09-04T15:19:55.573 回答