R中矩阵中矢量元素的差异

时间:2012-11-12 23:22:02

标签: r

我有x的向量。我想创建一个对元素矩阵,它们的差异小于或等于1e-2。我怎么能在R?中做到这一点?

    x = c(0.0001560653, 0.0001685597, 0.0002793819, 0.0006336307, 0.0455676525,
    0.3184740837, 0.3195122279, 0.3195122606)

    i = which(diff(x) <= 1e-2)

我想要的矩阵如下:

    > M
         [,1]         [,2]
  [1,] 0.0001560653 0.0001685597
  [2,] 0.0001685597 0.0002793819
  [3,] 0.0002793819 0.0006336307
  [4,] 0.3184740837 0.3195122279
  [5,] 0.3195122279 0.3195122606

2 个答案:

答案 0 :(得分:2)

就像那样:

idx <- which(diff(x) <= 0.01)
cbind(x[idx], x[idx+1])
#              [,1]         [,2]
# [1,] 0.0001560653 0.0001685597
# [2,] 0.0001685597 0.0002793819
# [3,] 0.0002793819 0.0006336307
# [4,] 0.3184740837 0.3195122279
# [5,] 0.3195122279 0.3195122606

答案 1 :(得分:1)

您可以使用expand.grid

x <- c(0.0001560653, 0.0001685597, 0.0002793819, 0.0006336307, 0.0455676525,
0.3184740837, 0.3195122279, 0.3195122606)
y <- expand.grid(x,x)
as.matrix(y[abs(y[[2]] - y[[1]]) <= 0.01,])

           Var1         Var2
1  0.0001560653 0.0001560653
2  0.0001685597 0.0001560653
3  0.0002793819 0.0001560653
4  0.0006336307 0.0001560653
9  0.0001560653 0.0001685597
10 0.0001685597 0.0001685597
11 0.0002793819 0.0001685597
...

更新:已编辑以反映已编辑问题中的所需输出。