0

我在 R 中有一个 50 列 x 250 万行的数据框,代表一个时间序列。时间列属于 POSIXct 类。为了分析,我反复需要在特定时间找到给定类的系统状态。

我目前的方法如下(简化且可重复):

set.seed(1)
N <- 10000
.time <- sort(sample(1:(100*N),N))
class(.time) <- c("POSIXct", "POSIXt")
df <- data.frame(
  time=.time,
  distance1=sort(sample(1:(100*N),N)),
  distance2=sort(sample(1:(100*N),N)),
  letter=sample(letters,N,replace=TRUE)
)

# state search function
time.state <- function(df,searchtime,searchclass){
  # find all rows in between the searchtime and a while (here 10k seconds)
  # before that
  rows <- which(findInterval(df$time,c(searchtime-10000,searchtime))==1)
  # find the latest state of the given class within the search interval
  return(rev(rows)[match(T,rev(df[rows,"letter"]==searchclass))])
}  

# evaluate the function to retrieve the latest known state of the system
# at time 500,000.
df[time.state(df,500000,"a"),]

但是,调用的which成本非常高。或者,我可以先按类过滤,然后找到时间,但这并不会改变评估时间。根据 Rprof 的说法,这which花费==了大部分时间。

有没有更有效的解决方案?时间点按弱递增排序。

4

1 回答 1

1

因为which,==[都与数据帧的大小成线性关系,所以解决方法是生成子集数据帧进行批量操作,如下:

# function that applies time.state to a series of time/class cominations
time.states <- function(df,times,classes,day.length=24){
  result <- vector("list",length(times))
  day.end <- 0
  for(i in 1:length(times)){
    if(times[i] > day.end){
      # create subset interval from 1h before to 24h after
      day.begin <- times[i]-60*60
      day.end <- times[i]+day.length*60*60
      df.subset <- df[findInterval(df$time,c(day.begin,day.end))==1,]
    }
    # save the resulting row from data frame
    result[[i]] <- df.subset[time.state(df.subset,times[i],classes[i]),]
  }
  return(do.call("rbind",result))
}

随着dT=diff(range(df$times))dT/day.length大,这减少了一个因子的评估时间dT/(day.length+1)

于 2013-02-01T12:13:56.473 回答