R通过函数添加许多列

时间:2013-04-25 12:55:25

标签: r

我试图通过下一个代码在图层中剪切数字:

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的cols)+ 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

我尝试了不同的形式,并且一直有尺寸错误。

此致

1 个答案:

答案 0 :(得分: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