Using read.zoo instead of read.table and zoo()?
-
26-09-2019 - |
문제
I have a file with many rows of this kind
2010-01-12 19:40 1021.00000 0.00001 1.00
2010-01-12 19:50 1031.00000 0.00000 -1.00
In order to read it as zoo I use
tmp <- read.table("myfile")
GOEMD <- zoo(tmp[,3], as.chron(paste(tmp[,1],tmp[,2]), format="%Y-%m-%d %H:%M"))
that works properly
But I'd like to use read.zoo()
instead.
I've tried
f <- function(x) as.chron(paste(tmp[,1],tmp[,2]))
tmp <- read.zoo("myfile", index = 1:2, sep=" ", FUN = f)
and even specifying
colClasses= c("character","character","numeric","numeric","numeric")
but it doesn't work; it says: line 136 (the one I've pasted above) doesn't have 14 elements.
I've also tried:
tmp <- read.zoo("myfile", index = 1:2, sep=" ", FUN = as.chron)
해결책
- The typo in
f
was already pointed out. - Also there are a few features of
read.zoo
that you might wish to take advantage of. Firstly, note that if the value of theindex
argument is a list then the columns referenced in each component of that list are passed as separate arguments toFUN
. Also note that aFUN2
argument is available which is applied to the output ofFUN
so we can write it in a compact fashion like this:
Thus try this:
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)
The above was written to be self contained so you could just copy it verbatim to the clipboard and then paste it into your R session. To use it with your file replace textConnection(Lines)
with "myfile"
.
다른 팁
Your function f
has to search for tmp
. You probably intended:
f <- function(x) as.chron(paste(x[,1],x[,2]))
tmp <- read.zoo("myfile", index = 1:2, sep=" ", FUN = f)
Also, the sample data you posted looks like it's tab-delimited, not space-delimited, so you may need to this instead:
tmp <- read.zoo("myfile", index = 1, sep="\t", FUN = as.chron)
제휴하지 않습니다 StackOverflow