tags:

views:

54

answers:

2

I'd like to convert my csv files into xts objects as efficiently as possible. I seem to be stuck though with having to first applying the read.zoo method to create a zoo objects before being able to convert it to an xts object.

gold <- read.zoo("GOLD.CSV", sep=",", format="%m/%d/%Y", header=TRUE)

Gold <- as.xts (gold, order.by=index(gold), frequency=NULL)

Is this the most efficient way of converting my initial GOLD.CSV file into an R xts object?

+2  A: 

If it is a file, you need to read it.

So use read.zoo() as you -- but then convert rightaway:

 gold <- as.xts(read.zoo("GOLD.CSV", sep=",", format="%m/%d/%Y", header=TRUE))

Ok?

Dirk Eddelbuettel
That works! I'm not clear how you can avoid passing the order.by argument. In any case, I'm not sure you can beat that line for efficiency. It appears there is no read.xts function in existence or in the works.
Milktrader
If it is already a `zoo` object, it has an index and does not need `order.by`.
Dirk Eddelbuettel
@Milktrader, I think you're confusing `xts` and `as.xts`. Compare `args(xts:::as.xts.zoo)` and `args(xts)`.
Joshua Ulrich
Dirk, Joshua thanks for your answers.
Milktrader
+1  A: 

You can write your own read.xts function. We would call it a wrapper function and it should go something along the lines of

read.xts <- function(x, format = "%m/%d/%Y", header = TRUE, sep = ",") {
  result <- as.xts(read.zoo(x, sep = sep, format = format, header = header))
  return(result)
}

read.xts(file.choose())  # select your file

Notice the arguments in function(). They are passed to the body of the function (code between curly braces). If function() arguments have values, this means that this is their default. If you assign new values (e.g. function(x = "my.file.csv", sep = "\t")), they will overwrite the defaults. The last line shows you how you can use your new function. Feel free to extend this function with the rest of the read.zoo arguments. Should you have any specific question on how to do it, don't by shy and just ask. :)

I use a few of little gems like that in my daily work. I've created a file called workhorse.R and I load it (e.g. source("d:/workspace/workhorse.R")) whenever I need any of the little functions.

Roman Luštrik
A most excellent idea that I didn't consider as I'm still pre-function writing in my R knowledge. Functions are next for me, so this is a perfect application. Also, appreciate you defining 'wrapper' function as this phrase has been opaque to me. Starting to sink in now.
Milktrader
Have no fear --- it can be as simple as a oneliner: `cubed <- function(x) x^3`. Now try `cubed(1:3)`.
Dirk Eddelbuettel
I tried it Dirk, and I like it. Thanks mate.
Milktrader