开发者

data.frame object to xts object conversion in R

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?


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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜