David Lee - 1 year ago 104
R Question

# Why split() in R split matrix into vector and how can I get the matrix result?

I want to split a matrix into two parts. I used following code

``````x <- matrix(rnorm(15),5,3)
idx <- rbinom(5,1,0.5)
split(x,idx)
``````

However, I got two vector instead two matrix. I know if I convert
`x`
to data.frame will get what I want. i.e.

``````x <- as.data.frame(matrix(rnorm(15),5,3))
idx <- rbinom(5,1,0.5)
split(x,idx)
``````

I wonder is there any way without convert matrix into data frame and result still in the matrix format? And why this happened?

`split.data.frame(x,idx)` maybe? That will force the `split` operation to treat your `matrix` like a `data.frame`, instead of as a `vector` with dimensions (which essentially describes a `matrix`).

Example showing it gives essentially the same result, but with a `matrix` instead of `data.frame` returned:

``````set.seed(1)
x <- matrix(rnorm(15),5,3)
idx <- rbinom(5,1,0.5)
split.data.frame(x,idx)
#\$`0`
#           [,1]       [,2]       [,3]
#[1,] -0.6264538 -0.8204684  1.5117812
#[2,] -0.8356286  0.7383247 -0.6212406
#[3,]  1.5952808  0.5757814 -2.2146999
#
#\$`1`
#          [,1]       [,2]      [,3]
#[1,] 0.1836433  0.4874291 0.3898432
#[2,] 0.3295078 -0.3053884 1.1249309

split(data.frame(x),idx)
#\$`0`
#          X1         X2         X3
#1 -0.6264538 -0.8204684  1.5117812
#3 -0.8356286  0.7383247 -0.6212406
#4  1.5952808  0.5757814 -2.2146999
#
#\$`1`
#         X1         X2        X3
#2 0.1836433  0.4874291 0.3898432
#5 0.3295078 -0.3053884 1.1249309
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download