R 应用 Return 子矩阵

R apply Return submatrix

鉴于此代码:

test=matrix(c(1,2,3,4,5,6,7,8,9,10,11,12),4)
splitData=data.frame(first=c(1,3),second=c(2,4))
apply(splitData,1,function (x) {test[x[1]:x[2],]})

我得到这个矩阵:

     [,1] [,2]
[1,]    1    3
[2,]    2    4
[3,]    5    7
[4,]    6    8
[5,]    9   11
[6,]   10   12

为什么我没有得到矩阵列表?

预期结果:

[[1]]
     [,1] [,2] [,3]
[1,]    1    5    9
[2,]    2    6   10

[[2]]
     [,1] [,2] [,3]
[1,]    3    7   11
[2,]    4    8   12

你可以试试

do.call(`c`,apply(splitData, 1, function(x) list(test[x,])))

或者

lapply(seq_len(nrow(splitData)), function(i)  test[unlist(splitData[i,]),])

来自?apply

If each call to ‘FUN’ returns a vector of length ‘n’, then ‘apply’ returns an array of dimension ‘c(n, dim(X)[MARGIN])’ if ‘n > 1’. If ‘n’ equals ‘1’, ‘apply’ returns a vector if ‘MARGIN’ has length 1 and an array of dimension ‘dim(X)[MARGIN]’ otherwise. If ‘n’ is ‘0’, the result has length 0 but not necessarily the ‘correct’ dimension. If the calls to ‘FUN’ return vectors of different lengths, ‘apply’ returns a list of length ‘prod(dim(X)[MARGIN])’ with ‘dim’ set to ‘MARGIN’ if this has length greater than one.