简体   繁体   English

R:间隔中的点均等,但不包括端点

[英]R: equally space points in an interval but not include the endpoints

Suppose I want to generate equally spaced points within an interval in R, I found the seq function will do this, but the results shows as: 假设我想在R的间隔内生成等距的点,我发现seq函数可以做到这一点,但结果显示为:

seq(0, 1, length.out = 10)
[1] 0.0000000 0.1111111 0.2222222 0.3333333 0.4444444 0.5555556 0.6666667
[8] 0.7777778 0.8888889 1.0000000

If we want to generate 0.1, 0.2,...,0.9, 1.0 , how could I include one end point and not the other one? 如果我们要生成0.1, 0.2,...,0.9, 1.0我该如何包含一个端点而不包含另一个端点?

Thanks! 谢谢!

Another option similar to @duckmayr's answer with an additional aligned argument 另一个选项类似于@duckmayr的答案,带有附加的aligned参数

fun <- function(minimum, maximum, length_out, aligned = c("left", "right")) {
  type <- match.arg(aligned)
  step <- maximum / length_out

  if(type == "left") {
    seq(minimum, right - step, length.out = length_out)
  } else {
    seq(minimum + step, right, length.out = length_out)
  }
}

fun(0, 1, 10) # default is "left"
# [1] 0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9

fun(0, 1, 10, "right")
# [1] 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0

fun(0, 1, 10, "abc")

error in match.arg(aligned) : 'arg' should be one of “left”, “right” match.arg(aligned)中的错误:“ arg”应为“ left”,“ right”之一

You could do that programatically with something like this: 您可以使用以下方式以编程方式执行此操作:

f <- function(from, to, length.out) {
    length.out <- length.out + 1
    result <- seq(from, to, length.out = length.out)
    result <- result[-1]
    return(result)
}

f(0, 1, 10)
# [1] 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0

The idea is that we'll make a sequence with length one more than what you actually want; 这个想法是,我们将使序列的长度比您实际想要的多一; this will space the elements how you want them, then we just discard the unwanted initial element. 这将以您想要的方式分隔元素,然后我们只丢弃不需要的初始元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM