[英]peak selection using window in R
I have a data set like this: 我有一个这样的数据集:
Just 1 table with 2 columns. 只有1张桌子和2列。 The first column runs from 1 to 100 and in the second we have random numbers.
第一列为1到100,第二列为随机数。 for eg
例如
x y
1 25
2 51
3 250
- --
48 250
49 500
50 1000
- --- --and so on till
100 600
Now , I need to choose a window of first 50 rows (x = 1 to x= 50). 现在,我需要选择前50行的窗口(x = 1至x = 50)。 Take the value of y corresponding to x = 50 (here y=1000 for x=50) and take the ratio of y(x = 50) to y(x = 49) ..here it is 1000 / 500 = 2... and the ratio of y(x = 50) to y(x = 48) ..here it is 1000 / 250 = 4.. and so on till y(x = 50) to y(x = 1) and then take the average of these fifty ratios.
取对应于x = 50的y值(对于x = 50,此处y = 1000),并取y(x = 50)与y(x = 49)的比率。此处为1000/500 = 2。 。和y(x = 50)与y(x = 48)之比..这里是1000/250 =4。依此类推,直到y(x = 50)与y(x = 1),然后取这五十个比率的平均值。
till this part, it was easy. 到目前为止,这很容易。
after this I need to move the window by 1 position for eg from x = 2 to x= 51 and repeat everything till the window reaches x= 51 to x=100. 之后,我需要将窗口移动1个位置,例如从x = 2到x = 51,并重复所有操作,直到窗口达到x = 51到x = 100。
I was thinking of using a time series window() function or rle() function or to use the subset() function in a for loop or to use apply() function ? 我在考虑使用时间序列window()函数或rle()函数,还是在for循环中使用subset()函数,或者使用apply()函数? what is the efficient way?
有效的方法是什么?
You are looking for rollapply
. 您正在寻找
rollapply
。
Using zoo
package: 使用
zoo
套餐:
library(zoo)
tt <- zoo(runif(100),order.by=seq_len(100))
rollapply(tt,width=50,
function(x)mean(tail(x,1)/x[-length(x)]))
PS : forget the mean function. PS:忘记均值功能。
In case you have some zeros values you can check the numerator using ifesle
: 如果您有一些零值,则可以使用
ifesle
检查分子:
filter_x <-
function(x){ vv = x[-length(x)]
vv = ifelse(vv>0,vv,1)
mean(tail(x,1)/vv)}
rollapply(tt,width=50,filter_x)
Use rollapply()
in the zoo
package: 在
zoo
包中使用rollapply()
:
library(zoo)
set.seed(1)
foo <- runif(100)
foo[c(58,59)] <- 0
rollapply(foo,width=50,FUN=function(xx){
foo <- xx[50]/xx[1:49]
mean(foo[is.finite(foo)],na.rm=TRUE)
}
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.