代码之家  ›  专栏  ›  技术社区  ›  skan

使用read.zoo而不是read.table和zoo()?

  •  2
  • skan  · 技术社区  · 15 年前

    我有一个文件有很多这样的行

    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)
    
    2 回复  |  直到 10 年前
        1
  •  3
  •   G. Grothendieck    15 年前
    1. 输入错误 f 已经指出了。
    2. 还有一些特性 read.zoo 你可能想利用它。首先,注意如果 index 参数是一个列表,然后该列表的每个组件中引用的列作为单独的参数传递给 FUN . 还要注意 FUN2 参数可用,该参数应用于 有趣的 所以我们可以这样简洁地写:

    因此,请尝试:

    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" .

        2
  •  2
  •   Joshua Ulrich    15 年前

    你的职能 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)