平滑算法实现(Zscore)

时间:2018-11-23 05:44:08

标签: r smoothing

我正在使用此算法进行研究Peak signal detection in realtime timeseries data时需要您的帮助。

我是R编程的初学者,试图在我的代码中实现该算法以具有平滑效果,我遇到了一些问题,并且我在代码中附加了错误日志,我知道的一点是,该算法适用于Vector输入和我的输入是在数据框中。

因此,如果有人可以帮助我,将不胜感激。

library(readr)
library(lubridate)
library(stringdist)
username = "MCF0600"
allWeeks <- split(dataset[dataset$user %in% username,]$activity, dataset[dataset$user %in% username,]$week) #Filter dataset to only include data relevent to chosen user.
indx <- sapply(allWeeks, length) #Convert the allWeeks variableinto DataFrame.
res <- as.data.frame(do.call(cbind,lapply(allWeeks, 'length<-',max(indx))))
res<-as.vector(t(res))
###############################################################################
########## Distance Calculation #############
w <- c()
for(i in 6:length(res))
{
  if (i <= length(res))
  {
    di <- seq_dist(na.omit(res[i]), na.omit(res[i-1]), method="dl")
    w[i - 5] <- di
  }
}
highestDist = 0;
for(result in w)
{
  if ((result) > highestDist)
  {
    highestDist = result
  }
}
hd_week = match(highestDist, w) + 5
plot(6:(length(res)), w[1:(length(w))], type="l", xlab="Week", ylab="DL Distance ", main=paste("DL Distance for", username, sep=" "))
text(x=hd_week, y=highestDist, label=hd_week)

#####################################################
########## Distance Calculation #############

y <- res
ThresholdingAlgo <- function(y,lag,threshold,influence) 
  {
  signals <- rep(0,length(y))
  filteredy <- y[0:lag]
  avgFilter <- NULL
  stdFilter <- NULL
  avgFilter[lag] <- mean(y[0:lag])
  stdFilter[lag] <- sd(y[0:lag])

# Run algo with lag = 30, threshold = 5, influence = 0
#plot(result$signals,type="S",col="red",ylab="",xlab="",ylim=c(-1.5,1.5),lwd=2)


  for (i in (lag+1):length(y)){
    if (abs(y[i]-avgFilter[i-1]) > threshold*stdFilter[i-1]) 
      {
      if (y[i] > avgFilter[i-1]) 
        {
        signals[i] <- 1;
      } 
      else {
        signals[i] <- -1;
      }
      filteredy[i] <- influence*y[i]+(1-influence)*filteredy[i-1]
    } else {
      signals[i] <- 0
      filteredy[i] <- y[i]
    }
    avgFilter[i] <- mean(filteredy[(i-lag):i])
    stdFilter[i] <- sd(filteredy[(i-lag):i])
  }
  return(list("signals"=signals,"avgFilter"=avgFilter,"stdFilter"=stdFilter))
}

lag       <- 25
threshold <- 5
influence <- 0

# Run algo with lag = 30, threshold = 5, influence = 0
result <- ThresholdingAlgo(y,lag,threshold,influence)
plot(result$signals,type="l",col="red",ylab="",xlab="",ylim=c(-1.5,1.5),lwd=2)

##################### ERROR LOG#############################################



Error in is.data.frame(x) : 
  (list) object cannot be coerced to type 'double'
In addition: Warning message:
In mean.default(y[0:lag]) :

 Hide Traceback

 Rerun with Debug
 Error in is.data.frame(x) : 
  (list) object cannot be coerced to type 'double' 
4.
is.data.frame(x) 
3.
var(if (is.vector(x) || is.factor(x)) x else as.double(x), na.rm = na.rm) 
2.
sd(y[0:lag]) 
1.

0 个答案:

没有答案
相关问题