【问题标题】:Convert data from csv file into "xts" object将数据从 csv 文件转换为“xts”对象
【发布时间】:2011-06-12 23:08:04
【问题描述】:

我有 CSV 文件,其日期格式如下: 2004 年 8 月 25 日

我想将其读取为“xts”对象,以便使用 quantmod 包中的“periodReturn”函数。

我可以将以下文件用于该功能吗?

Symbol Series        Date Prev.Close Open.Price High.Price Low.Price

1       XXX     EQ 25-Aug-2004     850.00    1198.70    1198.70    979.00

2       XXX     EQ 26-Aug-2004     987.95     992.00     997.00    975.30

用同样的方法指导我。

【问题讨论】:

    标签: r csv xts import-from-csv


    【解决方案1】:

    不幸的是,我不能代表ts 部分,但这是您可以将日期转换为其他函数可以读取为日期(或时间)的正确格式的方法。 您可以像往常一样将数据导入 data.frame (see here if you've missed it)。然后,您可以使用strptime 函数将您的Date 列转换为POSIXlt (POSIXt) 类。

    nibha <- "25-Aug-2004" # this should be your imported column
    lct <- Sys.getlocale("LC_TIME"); Sys.setlocale("LC_TIME", "C") #temporarily change locale to C if you happen go get NAs
    strptime(nibha, format = "%d-%b-%Y")
    Sys.setlocale("LC_TIME", lct) #revert back to your locale
    

    【讨论】:

    • 谢谢罗马..我已经转换了数据..我会检查“xts”部分..再次感谢:)
    【解决方案2】:

    试试这个。我们去掉讨厌的列,指定时间索引的格式,然后转换成 xts 并应用 dailyReturn 函数:

    Lines <- "Symbol Series Date Prev.Close Open.Price High.Price Low.Price
    1 XXX EQ 25-Aug-2004 850.00 1198.70 1198.70 979.00
    2 XXX EQ 26-Aug-2004 987.95 992.00 997.00 975.30"
    
    library(quantmod) # this also pulls in xts & zoo
    
    z <- read.zoo(textConnection(Lines), format = "%d-%b-%Y",
        colClasses = rep(c(NA, "NULL", NA), c(1, 2, 5)))
    x <- as.xts(z)
    dailyReturn(x)
    

    当然,textConnection(Lines) 只是为了保持示例的独立性,实际上会被替换为 "myfile.dat" 之类的东西。

    【讨论】:

      猜你喜欢
      • 2013-04-21
      • 2017-04-21
      • 2016-01-07
      • 2023-03-14
      • 1970-01-01
      • 1970-01-01
      • 2019-01-22
      • 2018-01-17
      • 2018-09-03
      相关资源
      最近更新 更多