This method can be used when you want to derive the flag of an aggregate that is a weighted average, index, quantile, etc.
flag_weighted(i, f, w)
i | An integer column identifier of data.frame or a matrix containing the flags and weights used to derived the flag for the aggregates. |
---|---|
f | A data.frame or a matrix containing the flags of the series (one column per period) |
w | A data.frame or a matrix with same size and dimesion as |
flag_weighted
Returns a character vector with the flag that has the highest weighted frequency or multiple flags in alphabetical
order (in case there are more than one flag with the same highest weight) as the first value, and the sum of weights for the given flag(s) as
the second value for the given columns of f,w
defined by the parameter i
.
flag_weighted(1, data.frame(f=c("pe","b","p","p","u","e","d"), stringsAsFactors = FALSE), data.frame(w=c(10,3,7,12,31,9,54)))#> [1] "d" "54"flag_weighted(1, data.frame(f=c("pe","b","p","p","up","e","d"), stringsAsFactors = FALSE), data.frame(w=c(10,3,7,12,31,9,54)))#> [1] "p" "60"flag_weighted(1, data.frame(f=c("pe",NA,"pe",NA,NA,"d"), stringsAsFactors = FALSE), data.frame(w=c(10,3,7,12,31,9)))#> [1] "e, p" "17"flags <- tidyr::spread(test_data[, c(1:3)], key = time, value = flags) weights <- tidyr::spread(test_data[, c(1, 3:4)], key = time, value = values) flag_weighted(7,flags[, c(2:ncol(flags))],weights[, c(2:ncol(weights))])#> [1] "p" "69330.0312141362"weights<-apply(weights[, c(2:ncol(weights))],2,function(x) x/sum(x,na.rm=TRUE)) weights[is.na(weights)] <- 0 flags<-flags[, c(2:ncol(flags))] sapply(1:ncol(flags),flag_weighted,f=flags,w=weights)#> [,1] [,2] [,3] #> [1,] "p" "s" "e" #> [2,] "0.0422086492915347" "0.0523619060166766" "0.133211654011488" #> [,4] [,5] [,6] #> [1,] "u" "u" "p" #> [2,] "0.124148695828608" "0.0766515426851311" "0.174097815337322" #> [,7] #> [1,] "p" #> [2,] "0.335586943761588"