如何将自定义函数累积应用于 R 中的向量?以一种有效和惯用的方式? [英] How can I cumulatively apply a custom function to a vector in R? In an efficient and idiomatic way?

查看:14
本文介绍了如何将自定义函数累积应用于 R 中的向量?以一种有效和惯用的方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道 R 中的函数 cumsum 计算其向量参数的累积和.

I know the function cumsum in R which compute a cumulative sum of its vector argument.

我需要累积应用"的不是 sum 函数,而是泛型函数,在我的特定情况下,是 quantile 函数.

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

它有效,但效率不高,我觉得在 R 中应该有一种更惯用的方法.

It works but it is not efficient and I feel there should be a more idiomatic way of doing it in R.

推荐答案

您可以使用这种方法:

set.seed(42)
df <- data.frame(measurement = rnorm(1000))

res <- sapply(seq(nrow(df)), function(x) 
  quantile(df[seq(x), "measurement"], c(.01, .99)))

它创建了一个具有 nrow(df) 列和 2 行的矩阵,其中一行用于第 1 个百分位数,一行用于第 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.

您可以将此信息添加到您的数据框 df(作为两个 olumns):

You can add this information to you data frame df (as two olumns):

df <- setNames(cbind(df, t(res)), c(names(df), "lower", "upper"))

这篇关于如何将自定义函数累积应用于 R 中的向量?以一种有效和惯用的方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆