【问题标题】:Convert Dataframe object into xts将 Dataframe 对象转换为 xts
【发布时间】:2018-09-03 01:09:44
【问题描述】:
> df <- read.csv("C:\\Users\\Vikas Kumar Dwivedi\\Desktop\\Yahoo.csv")
> df
         Date        Open        High         Low       Close   Adj.Close      Volume
1  01-03-2013        null        null        null        null        null        null
2  01-04-2013 1569.180054 1597.569946 1536.030029 1597.569946 1597.569946 77098000000
3  01-05-2013 1597.550049 1687.180054 1581.280029  1630.73999  1630.73999 76447250000


> df$Date <- as.Date(df$Date, format("%m/%d/%Y"))
> df <- df[order(df$Date), ]
> df<- as.xts(df[, 2], order.by = df$Date)
Error in UseMethod("as.xts") : 
  no applicable method for 'as.xts' applied to an object of class "factor"

我无法将数据帧转换为 xts?你能帮帮我吗?

【问题讨论】:

  • 请提供csv的前几行。
  • 我支持 G. Grothendieck 的评论...以表格形式读取文本会导致与您必须使用的数据结构不同,因为代码在 as.Date 上失败。

标签: r xts


【解决方案1】:

问题在于 CSV 中的列包含数字和字符,因此 read.csv() 将它们解释为因子。你需要做quantmod::getSymbols.yahoo() 所做的事情并设置na.strings = "null"。这告诉read.csv() 将字符串"null" 视为NA 值。

csv <- "Date,Open,High,Low,Close,Adj.Close,Volume
01-03-2013,null,null,null,null,null,null
01-04-2013,1569.180054,1597.569946,1536.030029,1597.569946,1597.569946,77098000000
01-05-2013,1597.550049,1687.180054,1581.280029,1630.73999,1630.73999,76447250000"
d <- read.csv(text = csv, na.strings = "null")
# also note that your date format was wrong, and there is no need to wrap a character
# string in `format()`
d$Date <- as.Date(d$Date, format = "%m-%d-%Y")
#d <- d[order(d$Date), ]  # this isn't necessary, xts() will do it for you
(x <- xts(d[, 2], order.by = d$Date))
#               [,1]
# 2013-01-03      NA
# 2013-01-04 1569.18
# 2013-01-05 1597.55

或者,如果您更喜欢 xts 对象,您可以通过调用 read.csv.zoo() 并将其包装在 as.xts() 中来完成所有这些操作。

(x <- as.xts(read.csv.zoo(text = csv, format = "%m-%d-%Y", na.strings = "null")))
#               Open    High     Low   Close Adj.Close      Volume
# 2013-01-03      NA      NA      NA      NA        NA          NA
# 2013-01-04 1569.18 1597.57 1536.03 1597.57   1597.57 77098000000
# 2013-01-05 1597.55 1687.18 1581.28 1630.74   1630.74 76447250000

【讨论】:

    猜你喜欢
    • 2017-04-21
    • 1970-01-01
    • 2016-01-07
    • 2023-03-14
    • 2018-01-17
    • 1970-01-01
    • 1970-01-01
    • 2020-03-07
    • 2014-05-17
    相关资源
    最近更新 更多