-2

Essentially (in R), I want to apply a moving average function over a period of time (eg. date and time variables) to see how a particular metric changes over time. However, the metric in itself is a function. The scores can either be 1 (pro), 0 (neutral), or -1 (neg). The function for the metric is:

function(pro, neg, total) {
x <- (pro / total) * 100
y <- (neg / total) * 100
x - y
}

So the percentage of 1's minus the percentage of -1's is the metric value.

Given timestamps for each recorded score, I want to evaluate the metric as a moving average across all rows. I assumed that a for loop would be the best way to apply this but I am stuck in how to do this.

Does anyone have any thoughts / advice?

AkselA
  • 8,153
  • 2
  • 21
  • 34
kcaps
  • 9
  • 1
  • 1
    You probably want some variation of `rollapply` from the [zoo package](https://www.rdocumentation.org/packages/zoo/versions/1.8-5/topics/rollapply). Post some example data and expected output to help answerers give more details – jeremycg Apr 17 '19 at 20:21

1 Answers1

2

As mentioned in the comments, rollapply() from zoo is a good option. I took the liberty to generate some example data, apologies if it doesn't resemble yours.

library(zoo)

f <- function(x, l) {
    p <- sum(x == 1) / l
    n <- sum(x == -1) / l
    (p - n)*100
}

# Or more efficiently
f <- function(x, l=length(x)) {
    (sum(x)/l)*100
}

set.seed(1)
N <- 25
dtf <- data.frame(time=as.Date(15000+(1:N)), score=sample(-1:1, N, rep=TRUE))

score <- read.zoo(dtf)
l <- 8
zts <- cbind(score, rolling=rollapply(score, l, f, l, fill=NA))

zts
#            score rolling
# 2011-01-27    -1      NA
# 2011-01-28     0      NA
# 2011-01-29     0      NA
# 2011-01-30     1    12.5
# 2011-01-31    -1    25.0
# 2011-02-01     1    12.5
# 2011-02-02     1     0.0
# 2011-02-03     0   -25.0
# 2011-02-04     0     0.0
# 2011-02-05    -1   -12.5
# 2011-02-06    -1   -12.5
# 2011-02-07    -1   -12.5
# 2011-02-08     1     0.0
# 2011-02-09     0    25.0
# 2011-02-10     1    37.5
# 2011-02-11     0    62.5
# 2011-02-12     1    62.5
# 2011-02-13     1    50.0
# 2011-02-14     0    37.5
# 2011-02-15     1    25.0
# 2011-02-16     1     0.0
# 2011-02-17    -1      NA
# 2011-02-18     0      NA
# 2011-02-19    -1      NA
# 2011-02-20    -1      NA
AkselA
  • 8,153
  • 2
  • 21
  • 34
  • This seems to work. Thank you for introducing the zoo package to me! I'll make sure to add it to my repertoire – kcaps Apr 18 '19 at 12:37