1

我试图通过下一个代码来减少层数:

X <- matrix(c(6,7,9,9,9,17,19,4,12,2,3,6,7,7),ncol=2)
layers <- c(5,10,15,20,25,30,35,40)
partitions <- function(u) {cbind(pmin(layers[1],u),t(diff(pmin(layers,u))))}
X <- cbind(X,lapply(X[,2], partitions))

该函数返回一个按层划分的整数。

A = a1 + a2 + .... + a8

例子

A <- 19
partitions(A)
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,]    5    5    5    4    0    0    0    0

但结果没有我需要的矩阵。最终矩阵为 7 x (2 (X 中的列) + 8 (层数))

     [,1] [,2]      [,3]
[1,] 6    Numeric,8 NULL
[2,] 7    Numeric,8 NULL
[3,] 9    Numeric,8 NULL
[4,] 9    Numeric,8 NULL
[5,] 9    Numeric,8 NULL
[6,] 17   Numeric,8 NULL
[7,] 19   Numeric,8 NULL
> dim(X)
[1] 7 3

我尝试了不同的形式并且曾经有尺寸错误。

问候

4

1 回答 1

1

这两个之一应该是你想要的

> rbind(t(X),sapply(X[,2], partitions))
      [,1] [,2] [,3] [,4] [,5] [,6] [,7]
 [1,]    6    7    9    9    9   17   19
 [2,]    4   12    2    3    6    7    7
 [3,]    4    5    2    3    5    5    5
 [4,]    0    5    0    0    1    2    2
 [5,]    0    2    0    0    0    0    0
 [6,]    0    0    0    0    0    0    0
 [7,]    0    0    0    0    0    0    0
 [8,]    0    0    0    0    0    0    0
 [9,]    0    0    0    0    0    0    0
[10,]    0    0    0    0    0    0    0

> cbind(X,t(sapply(X[,2], partitions)))
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,]    6    4    4    0    0    0    0    0    0     0
[2,]    7   12    5    5    2    0    0    0    0     0
[3,]    9    2    2    0    0    0    0    0    0     0
[4,]    9    3    3    0    0    0    0    0    0     0
[5,]    9    6    5    1    0    0    0    0    0     0
[6,]   17    7    5    2    0    0    0    0    0     0
[7,]   19    7    5    2    0    0    0    0    0     0
于 2013-04-25T13:37:09.973 回答