0

我正在尝试编写一个函数,将一些 xts 数据加载到R中,并按我指定的日期/时间对它们进行排序。也许我正在尝试一种过于简单的方法,但这是我的代码:

load.data <- function (x, time1, time2) #x is going to be the actual file name
{
    vector = get(load("C:/Users/username/Desktop/x"))
    sortvector = vector['time1/time2/']
    return (sortvector)
}

当我执行它时,我收到消息:

In readChar(con, 5L, useBytes = TRUE) :
  cannot open compressed file 'C:/Users/username/Desktop/x', probable reason 'No such file or directory'

那么,我怎样才能让我的函数真正搜索文件名,而不是实际的通用“x”?我希望我很清楚,我当然会非常感谢任何帮助。

4

1 回答 1

2

使用pastepaste0

load.data <- function (x, time1, time2) #x is going to be the actual file name
{
    vector = get(load(paste0("C:/Users/username/Desktop/", x)))
    sortvector = vector[paste(time1, time2, sep='/')]
    return(sortvector)
}

另外,查看?FinancialInstrument:::saveSymbols.daysand ?FinancialInstrument:::getSymbols.FI,或查看这些函数的代码以获取保存和加载xts对象的示例

编辑

这是一个例子

set.seed(123)
dat <- xts(cumsum(rnorm(100)), as.POSIXct("2012-05-23") + 1:100*60*60*6)
tmpdir <- tempdir()
save(dat, file=file.path(tmpdir, "dat.RData"))
rm('dat') 

time1 <- "2012-05-24 10:00:00"
time2 <- "2012-05-25 11:00:00"
vector = get(load(paste(tmpdir, "dat.RData", sep="/")))
sortvector = vector[paste(time1, time2, sep='/')]
sortvector
#                         [,1]
#2012-05-24 12:00:00 -2.044404
#2012-05-24 18:00:00 -2.829308
#2012-05-25 00:00:00 -4.497250
#2012-05-25 06:00:00 -4.877477
于 2012-07-08T20:22:33.110 回答