> 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?你能帮我吗?
答案 0 :(得分:0)
问题是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
或者你可以通过调用read.csv.zoo()
来完成所有这些操作,如果你喜欢xts对象,可以将它包装在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