简体   繁体   中英

Convert Dataframe object into xts

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

I am not able to convert dataframe into xts? Could you please help me.

The problem is that the columns in your CSV contain numbers and characters, so read.csv() interprets them as factors. You need to do what quantmod::getSymbols.yahoo() does and set na.strings = "null" . That tells read.csv() to treat the character string "null" as a NA value.

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

Or you can do all of this with a call to read.csv.zoo() and wrap it in as.xts() if you prefer an xts object.

(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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM