简体   繁体   中英

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 (eg 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 (eg source("d:/workspace/workhorse.R") ) whenever I need any of the little functions.

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