R-在一定范围内将向量中的元素计数为滑动窗口? [英] R - Counting elements in a vector within a certain range, as a sliding window?
问题描述
我正在使用R,我想将整数的标准向量转换为2列数据帧,以显示每个向量中属于指定大小窗口的元素数。
I am using R and I would like to convert a standard vector of integers into a 2-column data frame showing the the number of elements in each vector that fall within a specified-sized window.
例如,使用此向量:
1, 75, 79, 90, 91, 92, 109, 120, 167, 198, 203, 204, 206, 224, 230,
236, 240, 245, 263, 344
在窗口大小为50的情况下查看值的结果应如下所示:
The results for looking at the values that fall with in a window-size of 50 should look like this:
50 1
100 5
150 2
200 2
250 8
300 1
350 1
400 0
第一列为数字范围,第二列为该范围内的计数。
With the first column as the number range, and the second as the count within that range.
这表明对于1-50范围,该范围内有1个元素;对于51-100,范围内有5个元素;对于101-150范围内,有2个元素等等,但是关键是窗口大小要灵活,因为我将使用它进行多次分析。
This shows that for the range of 1-50 there is 1 element in that range, for 51-100 there are 5 elements, for 101-150 there are 2 elements, etc. It is key, however, that the window-size be flexible, as I will use this for multiple analyses.
推荐答案
这里有一些解决方案。
Here some solutions.
使用 cut
和 table
:
table(cut(vv,seq(min(vv),max(vv),50),include.lowest = TRUE))
[1,51] (51,101] (101,151] (151,201] (201,251] (251,301]
1 5 2 2 8 1
使用 findInterval
:
table(findInterval(vv,seq(min(vv),max(vv),50)))
1 2 3 4 5 6 7
1 5 2 2 8 1 1
使用晶格封装中的木瓦
:
shingle(vv,cbind(seq(min(vv),max(vv),50) ,seq(50,max(vv)+50,50)))
Intervals:
min max count
1 1 50 1
2 51 100 5
3 101 150 2
4 151 200 2
5 201 250 8
6 251 300 1
7 301 350 1
where `vv`:
c(1, 75, 79, 90, 91, 92, 109, 120, 167, 198, 203, 204, 206, 224,
230, 236, 240, 245, 263, 344)
这篇关于R-在一定范围内将向量中的元素计数为滑动窗口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!