how can I use rollapply with scale

时光毁灭记忆、已成空白 提交于 2021-01-29 08:13:44

问题


I have a data which can be generated like this:

set.seed(1)
foo <- sample(1:10000,1000)
foo[c(1:100)] <- 1

After this to get the zvalues, which are calculated by scale, I used:

boo<-rollapply(foo,50,scale)

But all the values of boo seems to be NAN.

background info:

z-score = scale = (x - mean)/ std deviation

My first question is why do I get NAN for all the values? For the first 100, I understand that std dev is o . So, I should get Nan only for the first few rows, but I get NAN for all the rows . I do not understand where I am wrong.

Second question is my actual problem.

I want to take a window of 50 elements and get the z-score only for the 25th or mid element of the window.Then I need to rollapply for all the 1000 datapoints.

So , the output will be z-score of elements from 25 to 975 for its respective 50 window size.How can i get this result using rollapply and scale?


回答1:


1) rollapply expects FUN to return a scalar or a vector, not a column matrix. Returning a vector will eliminate the unwanted NaN values:

rollapply(foo , 50, function(x) c(scale(x)))

The result will be a 951x50 matrix.

2) For the second question try this:

rollapply(foo, 50, function(x) (x[25] - mean(x)) / sd(x))

or this:

rollapply(foo, 50, function(x) scale(x)[25])

or this:

rollapply(foo, 50, function(x) c(scale(x)))[, 25]


来源:https://stackoverflow.com/questions/24247235/how-can-i-use-rollapply-with-scale

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