使用read.zoo代替read.table和zoo()?
-
26-09-2019 - |
题
我有一个包含很多行的文件
2010-01-12 19:40 1021.00000 0.00001 1.00
2010-01-12 19:50 1031.00000 0.00000 -1.00
为了将其读为动物园,我使用
tmp <- read.table("myfile")
GOEMD <- zoo(tmp[,3], as.chron(paste(tmp[,1],tmp[,2]), format="%Y-%m-%d %H:%M"))
它可以正常工作,但我想使用 read.zoo()
反而。
我试过了
f <- function(x) as.chron(paste(tmp[,1],tmp[,2]))
tmp <- read.zoo("myfile", index = 1:2, sep=" ", FUN = f)
甚至指定
colClasses= c("character","character","numeric","numeric","numeric")
但它不起作用;它说:第 136 行(我在上面粘贴的那一行)没有 14 个元素。
我也尝试过:
tmp <- read.zoo("myfile", index = 1:2, sep=" ", FUN = as.chron)
解决方案
- 中的错字
f
已经指出了。 - 另外还有几个特点
read.zoo
您可能希望利用它。首先,请注意,如果index
参数是一个列表,然后该列表的每个组件中引用的列作为单独的参数传递给FUN
. 。另请注意,FUN2
参数可用,应用于输出FUN
所以我们可以像这样紧凑地编写它:
因此尝试这个:
library(zoo)
library(chron)
Lines <- "2010-01-12 19:40 1021.00000 0.00001 1.00
2010-01-12 19:50 1031.00000 0.00000 -1.00"
z <- read.zoo(textConnection(Lines), index = list(1, 2),
FUN = paste, FUN2 = as.chron)
上面的内容是独立编写的,因此您可以将其逐字复制到剪贴板,然后将其粘贴到 R 会话中。要将其与文件替换一起使用 textConnection(Lines)
和 "myfile"
.
其他提示
您的功能f
必须搜索tmp
。你可能打算:
f <- function(x) as.chron(paste(x[,1],x[,2]))
tmp <- read.zoo("myfile", index = 1:2, sep=" ", FUN = f)
此外,您发布的样本数据看起来像它的制表符分隔,没有空格分隔,所以你可能需要这个来代替:
tmp <- read.zoo("myfile", index = 1, sep="\t", FUN = as.chron)
不隶属于 StackOverflow