Reputation: 18655
I know the function cumsum
in R which compute a cumulative sum of its vector argument.
I need to "cumulatively apply" not the sum function but a generic function, in my specific case, the quantile
function.
My current solution is based on a loop:
set.seed(42)
df<-data.frame(measurement=rnorm(1000),upper=0,lower=0)
for ( r in seq(1,nrow(df))){
df$upper[r]<-quantile(df[seq(1,r),"measurement"],c(.99))
df$lower[r]<-quantile(df[seq(1,r),"measurement"],c(.01))
}
x=seq(1,nrow(df))
plot(df$measurement,type="l",col="grey")
lines(x,df$upper,col="red")
lines(x,df$lower,col="blue")
It works but it is not efficient and I feel there should be a more idiomatic way of doing it in R.
Upvotes: 3
Views: 1296
Reputation: 81693
You can use this approach:
set.seed(42)
df <- data.frame(measurement = rnorm(1000))
res <- sapply(seq(nrow(df)), function(x)
quantile(df[seq(x), "measurement"], c(.01, .99)))
It creates a matrix with nrow(df)
columns and 2 rows, one row for the 1st percentile and one row for the 99th percentile.
You can add this information to you data frame df
(as two olumns):
df <- setNames(cbind(df, t(res)), c(names(df), "lower", "upper"))
Upvotes: 3