R:在一个间隔内相等间隔点,但不包括端点

R:在一个间隔内相等间隔点,但不包括端点,r,R,假设我想在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 如果我们要生成0.1、0.2、…、0.9、1.0,我怎么能包含一个端点而不包含另一个端点 谢谢 您可以通过以下方式编程实现: f <- fun

假设我想在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
如果我们要生成
0.1、0.2、…、0.9、1.0
,我怎么能包含一个端点而不包含另一个端点


谢谢

您可以通过以下方式编程实现:

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

f您可以通过以下方式编程实现:

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

f另一个选项类似于@duckmayr的答案,带有一个额外的
对齐的
参数

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")

fun另一个选项类似于@duckmayr的答案,带有一个额外的
对齐的
参数

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")

fun@markus在这种情况下,我每次都必须找到两点之间的距离,我需要在不同的时间间隔内进行此操作,因此我试图看看是否有更简单的方法来进行此操作。将此作为注释,因为我不知怎的认为这不是您要寻找的。怎么样:
n@markus说得好,和我的方法非常相似below@markus是的,谢谢,这正是我要找的。老实说,这和我现在使用的方法非常相似。但我想知道是否有其他函数可以通过指定一些参数的值来实现这一点?请看一下
?这可能也有帮助。例如,
pretty(1:10,n=10)/10
@markus在这种情况下,我每次都必须找到两点之间的距离,我需要在不同的时间间隔内进行此操作,因此我试图看看是否有更简单的方法来进行此操作。将此作为注释保留,因为我不知怎的认为这不是您想要的。怎么样:
n@markus说得好,和我的方法非常相似below@markus是的,谢谢,这正是我要找的。老实说,这和我现在使用的方法非常相似。但我想知道是否有其他函数可以通过指定一些参数的值来实现这一点?请看一下
?这可能也有帮助。例如,
pretty(1:10,n=10)/10