给出一个矢量(一个数据帧的列),我想创建一个滚动矢量。
#top-level {
background: #90c0ff;
height: 400px;
width: 600px;
}
#container {
background: #bbffbb;
height: 400px;
width: 400px;
display: inline-block;
position: relative;
text-align: center;
}
#inner {
height: 200px;
width: 200px;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
border: 1px solid black;
}
#adjacent {
background: #ff5050;
height: 395px;
width: 195px;
display: inline-block;
}
会返回(窗口为3):
<div id="top-level">
<div id="container">
<div id="inner">
Internal Text
</div>
</div>
<div id="adjacent">
Sample text
</div>
</div>
答案 0 :(得分:5)
1)滚动应用 r
是一个9x3矩阵,每个矩阵的行都是所请求的列表元素之一,split
将其转换为向量列表。尽管这满足了您的要求,但可能只是您要遍历该列表,在这种情况下,将c
替换为要在该迭代中使用的任何函数可能会更容易。例如rollapply(l, 3, sd)
library(zoo)
l <- 0:10 # test input
r <- rollapply(l, 3, c)
split(r, row(r))
给予:
$`1`
[1] 0 1 2
$`2`
[1] 1 2 3
$`3`
[1] 2 3 4
$`4`
[1] 3 4 5
$`5`
[1] 4 5 6
$`6`
[1] 5 6 7
$`7`
[1] 6 7 8
$`8`
[1] 7 8 9
$`9`
[1] 8 9 10
2)嵌入,也可以这样使用base R来完成:
r <- embed(l, 3)[, 3:1]
split(r, row(r))
答案 1 :(得分:0)
您可以使用以下函数(我假设您想先对值进行排序。如果没有,只需删除我正在使用sort()
的代码行):
roll<-function(list,window){
list<-sort(list,decreasing = FALSE)
res<-vector(mode = "list")
for(i in 1:(length(list) - window + 1)){
res[[i]]<-list[i:(i + window - 1)]
}
return(res)
}
在参数中输入您的列/列表值以及所需的窗口大小,它将为您提供所需的输出。
例如:
test<-0:10
roll(list = test,window = 3)
这将产生以下输出:
[[1]]
[1] 0 1 2
[[2]]
[1] 1 2 3
[[3]]
[1] 2 3 4
[[4]]
[1] 3 4 5
[[5]]
[1] 4 5 6
[[6]]
[1] 5 6 7
[[7]]
[1] 6 7 8
[[8]]
[1] 7 8 9
[[9]]
[1] 8 9 10
您可以在其他情况下使用此功能,甚至可以根据需要更改窗口大小。
希望有帮助!