序列扩展问题
我有一系列“端点”,例如:
c(7,10,5,11,15)
我想扩展到端点之间的一系列“经过时间”,例如
c(7,1,2,3,4,5,6,7,8,9,10,1,2,3,4,5 ,1,2, 3,4,5,6,7,8,9,10,11,1,2,3,4,5,6,7,8,9,10,11,12,13 ,14,15)
在 R 中执行此操作最有效的方法是什么?我正在想象对 embed
函数进行一些创造性的使用,但如果不使用丑陋的 for
循环,我就无法完全实现这一目标。
这是执行此操作的简单方法:
expandSequence <- function(x) {
out <- x[1]
for (y in (x[-1])) {
out <- c(out,seq(1,y))
}
return(out)
}
expandSequence(c(7,10,5,11,15))
I have a sequence of 'endpoints', e.g.:
c(7,10,5,11,15)
that I want to expand to a sequence of 'elapsed time' between the endpoints, e.g.
c(7,1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,1,2,3,4,5,6,7,8,9,10,11,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15)
Whats the most efficient way to do this in R? I'm imagining some creative use of the embed
function, but I can't quite get there without using a ugly for
loop.
Here's the naive way to do this:
expandSequence <- function(x) {
out <- x[1]
for (y in (x[-1])) {
out <- c(out,seq(1,y))
}
return(out)
}
expandSequence(c(7,10,5,11,15))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
有一个基本函数可以执行此操作,称为,等待它,
sequence
:在您的情况下,您的第一个端点似乎实际上不是序列的一部分,因此它变为:
There is a base function to do this, called, wait for it,
sequence
:In your case it seems your first endpoint is in fact not part of the sequence, so it becomes:
怎么样:
在最后添加第一个元素:
以及一个稍微更具可读性的版本:
How about this:
With the first element added on at the end:
And a slightly more readable version:
lapply()
和seq_len()
的组合在这里很有用:它给出了
(另一种选择是
:)
A combination of
lapply()
andseq_len()
is useful here:Which gives for
(An alternative is:
)