Question

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?

Was it helpful?

Solution

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?

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top