R 中 seq() 中缺少最后一个序列

Missing last sequence in seq() in R

我有这个示例数据

by<-200
to<-seq(from=by,to=35280,by=by)

问题是 to 以 35200 结束并忽略我需要作为最后一个值参与的最后 80 个。 有什么直接的方法可以实现它吗? 我已经尝试了 along.withlength.out 参数,但我无法进入低谷。

首先,seq() 的行为在您的示例中应该如此。您想要 seq() 本身无法提供的东西。

一个解决方案(肯定有很多)是在序列末尾检查天气 "there was anything left",如果是,则向其添加另一个元素。 (或者修改你序列的最后一个元素,你想要达到的目的并不完全清楚。)像这样:

step <- 200
end <- 35280
to<-seq(from=step,to=end,by=step)

# the modulus of your end point by step
m = end%%step 

# if not zero, you have something to add to your sequence
if(m != 0) {

    # add the end point
    to = c(to, end)
}

tail(to,2)
# 35200 35280

In seq(), "The second form generates from, from+by, ..., up to the sequence value less than or equal to to." 而且由于35280不在请求的序列中,所以没有返回。

但是您可以在要包含下一个值的参数中使用计算。由于您知道 to 值,请为其指定一个名称并使用它。

by <- 200
out <- 35280

x <- seq(from = by, to = (out + by - out %% by), by = by)

length(x)
# [1] 177
x[length(x)]
# [1] 35400

如果你想包含to值,即使它不在请求的序列中,你可以写一个小函数把它加回去

seqil <- function(..., include.last = TRUE) {
    x <- do.call(seq.default, list(...))
    if(include.last) c(x, to) else x
}

by <- 200

x <- seqil(from = by, to = 35280, by = by)
tail(x)
# [1] 34400 34600 34800 35000 35200 35280

您可以为向量的最后一个元素放置 if 语句,例如在以下函数中:

seqlast <- function (from, to, by) 
{
  vec <- do.call(what = seq, args = list(from, to, by))
  if ( tail(vec, 1) != to ) {
    return(c(vec, to))
  } else {
    return(vec)
  }
}

然后

by <- 200
to <- seqlast(from=by,to=35280,by=by)

将return

> head(to)
[1]  200  400  600  800 1000 1200
> tail(to)
[1] 34400 34600 34800 35000 35200 35280

虽然没有解决提出的确切问题,但我对此的首选解决方案是扩展序列以添加附加值,以便将 to 值包含在序列中,而不是仅在末尾附加 to 值。 这建立在@djas 和@Etienne Kintzler 的回答之上。

seq0 <- function(from = 1, to = 1, by = 1, incLast = TRUE){
    out = do.call(what = seq, args = list(from, to, by))
    if (incLast & to%%by != 0){
        out = c(out, tail(out, 1) + by) 
    } 
    return(out)
}

示例输出:

> seq0(from = 0, to = 20, by = 6, incLast = FALSE)
[1]  0  6 12 18
> seq0(from = 0, to = 20, by = 6, incLast = TRUE)
[1]  0  6 12 18 24
> seq0(from = 0, to = -20, by = -6, incLast = FALSE)
[1]   0  -6 -12 -18
> seq0(from = 0, to = -20, by = -6, incLast = TRUE)
[1]   0  -6 -12 -18 -24

这是对 Rich Scriven 答案的修改,在不需要时不添加额外的数字(与 20 一样)

by <- 2
out <- 21
out <- 20

x <- seq(from = 0, to = out + by*ifelse(out %% by>0,1,0) - out %% by , by = by)
x

您可以使用 c() 来包含最后一个数字。

by<-200
c(seq(from=by,to=35280,by=by), 35280)