如何在R中创建具有特定间隔的向量?

时间:2013-03-24 17:24:22

标签: r vector intervals

我有关于创建矢量的问题。如果我a <- 1:10,“a”的值为1,2,3,4,5,6,7,8,9,10。

我的问题是如何在元素之间创建具有特定间隔的向量。例如,我想创建一个值为1到100但仅以5为间隔计数的向量,以便得到一个值为5,10,15,20,...,95,100的向量

我认为在Matlab中我们可以1:5:100,我们如何使用R?

我可以尝试5*(1:20),但是有更短的方法吗? (因为在这种情况下,我需要知道整个长度(100),然后除以间隔(5)的大小得到20)

2 个答案:

答案 0 :(得分:63)

在R中,等效函数为seq,您可以将其与by选项一起使用:

seq(from = 5, to = 100, by = 5)
# [1]   5  10  15  20  25  30  35  40  45  50  55  60  65  70  75  80  85  90  95 100

除了by之外,您还可以使用其他选项,例如length.outalong.with

length.out :如果您想在0到1之间获得总共10个数字,例如:

seq(0, 1, length.out = 10)
# gives 10 equally spaced numbers from 0 to 1

along.with :它将您提供的矢量长度作为输入,并提供1:length(输入)的矢量。

seq(along.with=c(10,20,30))
# [1] 1 2 3

虽然不是使用along.with选项,但建议在这种情况下使用seq_along。来自?seq

的文档
  

seq是通用的,此处仅描述默认方法。请注意,它会调度第一个参数的类,而不管参数名称如何。如果仅使用一个参数来调用它可能会产生意想不到的后果,并且在这种情况下使用seq_along会更好。

seq_along:而不是seq(along.with(.))

seq_along(c(10,20,30))
# [1] 1 2 3

希望这有帮助。

答案 1 :(得分:0)

通常,我们希望将向量划分为多个间隔。 在这种情况下,您可以使用以下函数,其中(a)是向量, (b)是间隔数。 (假设您想要4个间隔)

a = 8
b = 23
c = 54
d = 89

... some code before and after

# FUNCTION - SOLVER CONSTRAINTS
def solver_constraint_1(t):
  return t[1] - t[0]
def solver_constraint_2(t):
  return t[2] - t[1]
def solver_constraint_3(t):
  return t[3] - t[2]

... some code before and after

x0 = [a, b, c, d, 1.0, 1.0, 1.0]

x_bounds = [[0, 20], [10, 60], [20, 80], [60, 100], [0.25, 2.5], [0.25, 2.5], [0.25, 2.5]]

x_cons = ({'type': 'ineq', 'fun': solver_constraint_1}, 
          {'type': 'ineq', 'fun': solver_constraint_2},    
          {'type': 'ineq', 'fun': solver_constraint_3})

solution = minimize(objective, x0, method='SLSQP', bounds=x_bounds, constraints=x_cons, options={'ftol': 1e-8, 'maxiter': 1000, 'disp': True})

因此,您有4个间隔:

a <- 1:10
b <- 4

FunctionIntervalM <- function(a,b) {
  seq(from=min(a), to = max(a), by = (max(a)-min(a))/b)
}

FunctionIntervalM(a,b)
# 1.00  3.25  5.50  7.75 10.00

您还可以使用剪切功能

1.00 - 3.25 
3.25 - 5.50
5.50 - 7.75
7.75 - 10.00