How can I cumulatively apply a custom function to a vector in R? In an efficient and idiomatic way?

て烟熏妆下的殇ゞ 提交于 2019-12-13 04:26:45

问题


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.


回答1:


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"))


来源:https://stackoverflow.com/questions/21796710/how-can-i-cumulatively-apply-a-custom-function-to-a-vector-in-r-in-an-efficient

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!