I have a csv file and extract data using
banknifty <- as.xts(read.zoo("banknifty.csv",sep=",",tz="" ,header=T))
read.zoo()
extracts the data frame with numeric values but as I apply as.xts()
, the data. frame
's numeric values get converted to characters.
# banknifty[1,] gives
2008-01-01 09.34:00 "10" "12" "13"
I want as.xts
should return data.frame
with numeric values.
How to avoid this problem?
You're confused about the nature of xts/zoo objects. They are matrices with an ordered index attribute, therefore you cannot mix types in xts/zoo objects like you can in a data.frame.
The reason your object is being converted to character is because some of the values in your file are not numeric. This is also why you get the NAs introduced by coercion
error when you tried hd1's solution.
So the answer to your question is, "fix your CSV file", but we can't help you fix it unless you show us the file's contents.
I just ran into a similar problem. In my case, the issue was that the as.xts() function tries to convert the date column along with the numeric columns. Because R does not consider dates to be numeric values, it automatically converts the entire data frame to character. I'm assuming that happens in your example as well (you can check this using your .csv-file).
Something like this should help:
data.in <- read.csv("banknifty.csv",sep=",",header=T)
data.in[,1] <- format(as.Date(data.in[,1]), format="%Y-%m-%d", tz="GMT", usetz=TRUE) #change tz to whatever applies
data.in[,1] <- as.POSIXct(data.in[,1], "GMT")
data.ts <- xts(data.in[,c(2,3,4,5)], order.by = data.in[,1])
(Note that data.ts <- xts(data.in, order.by = data.in[,1]) would replicate the unwanted conversion. Also, apologies that this is probably not the cleanest / most concise code, I'm still learning.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With