문제
R을 사용하여 행렬의 일련의 값에 대한 이동 평균을 계산하려고 합니다.하지만 일반적인 R 메일링 리스트 검색은 그다지 도움이 되지 않았습니다.없는 것 같습니다. 내장 기능 R에서는 이동 평균을 계산할 수 있습니다.패키지를 제공하는 패키지가 있나요?아니면 직접 작성해야 합니까?
다른 팁
또는 필터를 사용하여 간단히 계산할 수 있습니다. 여기에 내가 사용하는 기능이 있습니다.
ma <- function(x, n = 5){filter(x, rep(1 / n, n), sides = 2)}
사용하는 경우 dplyr
, 지정하도록주의하십시오 stats::filter
위의 기능에서.
사용 cumsum
충분하고 효율적이어야 합니다.벡터가 있다고 가정 엑스 그리고 당신은 누계를 원합니다 N 숫자
cx <- c(0,cumsum(x))
rsum <- (cx[(n+1):length(cx)] - cx[1:(length(cx) - n)]) / n
@mzuther의 의견에서 지적했듯이 이는 데이터에 NA가 없다고 가정합니다.이를 처리하려면 각 창을 NA가 아닌 값의 수로 나누어야 합니다.@Ricardo Cruz의 의견을 통합하는 한 가지 방법은 다음과 같습니다.
cx <- c(0, cumsum(ifelse(is.na(x), 0, x)))
cn <- c(0, cumsum(ifelse(is.na(x), 0, 1)))
rx <- cx[(n+1):length(cx)] - cx[1:(length(cx) - n)]
rn <- cn[(n+1):length(cx)] - cn[1:(length(cx) - n)]
rsum <- rx / rn
창의 모든 값이 NA인 경우 0으로 나누기 오류가 발생한다는 문제가 여전히 남아 있습니다.
~ 안에 데이터 1.12.0 새로운 frollmean
빠르고 정확한 롤링을 계산하기 위해 기능이 추가되었습니다. NA
, NaN
그리고 +Inf
, -Inf
가치.
질문에는 재현 가능한 사례가 없기 때문에 여기서 해결해야 할 것이 많지 않습니다.
자세한 정보를 찾을 수 있습니다 ?frollmean
매뉴얼에서 온라인으로도 제공됩니다 ?frollmean
.
아래 매뉴얼의 예 :
library(data.table)
d = as.data.table(list(1:6/2, 3:8/4))
# rollmean of single vector and single window
frollmean(d[, V1], 3)
# multiple columns at once
frollmean(d, 3)
# multiple windows at once
frollmean(d[, .(V1)], c(3, 4))
# multiple columns and multiple windows at once
frollmean(d, c(3, 4))
## three above are embarrassingly parallel using openmp
그만큼 caTools
패키지는 매우 빠른 롤링 평균/min/max/sd 및 기타 기능이 거의 없습니다. 나는 함께 일했다 runmean
그리고 runsd
그리고 그것들은 지금까지 언급 된 다른 패키지 중 가장 빠릅니다.
당신은 사용할 수 있습니다 RcppRoll
C ++로 작성된 매우 빠른 이동 평균. 그냥 전화하십시오 roll_mean
기능. 문서를 찾을 수 있습니다 여기.
그렇지 않으면 루프 의이 (느린)는 트릭을 수행해야합니다.
ma <- function(arr, n=15){
res = arr
for(i in n:length(arr)){
res[i] = mean(arr[(i-n):i])
}
res
}
사실로 RcppRoll
아주 좋습니다.
게시 된 코드 Cantdutch this 창으로의 네 번째 줄에서 수정해야합니다.
ma <- function(arr, n=15){
res = arr
for(i in n:length(arr)){
res[i] = mean(arr[(i-n+1):i])
}
res
}
놓친 또 다른 방법이 주어집니다 여기.
세 번째 방법, 개선 Cantdutch this 부분 평균을 계산하기위한 코드 : 다음과 같습니다.
ma <- function(x, n=2,parcial=TRUE){
res = x #set the first values
if (parcial==TRUE){
for(i in 1:length(x)){
t<-max(i-n+1,1)
res[i] = mean(x[t:i])
}
res
}else{
for(i in 1:length(x)){
t<-max(i-n+1,1)
res[i] = mean(x[t:i])
}
res[-c(seq(1,n-1,1))] #remove the n-1 first,i.e., res[c(-3,-4,...)]
}
}
답을 보완하기 위해 Cantdutch this 그리고 로드리고 레미 디오;
moving_fun <- function(x, w, FUN, ...) {
# x: a double vector
# w: the length of the window, i.e., the section of the vector selected to apply FUN
# FUN: a function that takes a vector and return a summarize value, e.g., mean, sum, etc.
# Given a double type vector apply a FUN over a moving window from left to the right,
# when a window boundary is not a legal section, i.e. lower_bound and i (upper bound)
# are not contained in the length of the vector, return a NA_real_
if (w < 1) {
stop("The length of the window 'w' must be greater than 0")
}
output <- x
for (i in 1:length(x)) {
# plus 1 because the index is inclusive with the upper_bound 'i'
lower_bound <- i - w + 1
if (lower_bound < 1) {
output[i] <- NA_real_
} else {
output[i] <- FUN(x[lower_bound:i, ...])
}
}
output
}
# example
v <- seq(1:10)
# compute a MA(2)
moving_fun(v, 2, mean)
# compute moving sum of two periods
moving_fun(v, 2, sum)
조금 느리지 만 동물원 :: rollapply를 사용하여 행렬에 대한 계산을 수행 할 수도 있습니다.
reqd_ma <- rollapply(x, FUN = mean, width = n)
여기서 x는 데이터 세트, fun = 평균은 함수입니다. Min, Max, SD 등으로 변경할 수 있으며 폭은 롤링 창입니다.