This is my first post. Apologies in advance if my question is dumb. I'm new to programming.
Ok, So I have a a matrix(eBpvalues)
in R that has 152720 rows and 2 columns.
I want to split into 10 separate matrices containing 15272 rows each.
I have tried this with:
> newmx <-split(as.data.frame(eBpvalues), rep(1:10, each = 15272)))
> summary(newmx)
Length Class Mode
1 2 data.frame list
2 2 data.frame list
3 2 data.frame list
4 2 data.frame list
5 2 data.frame list
6 2 data.frame list
7 2 data.frame list
8 2 data.frame list
9 2 data.frame list
10 2 data.frame list
How would I go about joining these matrices side-by-side so I have a new matrix with 20 columns and 15272 rows?
Cheers,
Neil
You are almost there. An often used function in these situations is do.call
, which takes a function you want to apply and a list of data to apply it to. The function you want to apply is cbind
to column bind the 10 data frames/matrices together.
Taking you literally, we start with a matrix mat
(eBpvalues
in your Q), of appropriate size. Convert to a data frame:
mat <- matrix(rnorm(152720 * 2), ncol = 2)
df <- data.frame(mat)
An easy way of producing an indicator factor is via the gl()
function:
ind <- gl(10, 15272)
Then we have your split()
call:
newMat <- split(df, ind)
The last step is this, where we us do.call()
to apply cbind()
to the set of data frames in newMat
:
res <- do.call(cbind, newMat)
This gives us what you wanted (although you might need to tidy the column names up etc).
> str(res)
'data.frame': 15272 obs. of 20 variables:
$ 1.X1 : num -0.268 -0.8568 -0.0267 1.0894 1.5847 ...
$ 1.X2 : num 0.71 -0.298 0.359 0.97 -2.158 ...
$ 2.X1 : num -0.987 -0.222 2.991 0.443 0.228 ...
$ 2.X2 : num -2.343 -1.023 -1.48 1.47 0.758 ...
$ 3.X1 : num -0.305 -0.761 0.817 1.347 0.694 ...
$ 3.X2 : num -0.0915 0.4816 1.4662 -1.2668 -1.3523 ...
$ 4.X1 : num -0.678 -1.056 1.029 -0.468 0.836 ...
$ 4.X2 : num -0.656 -0.459 -0.965 -1.666 0.877 ...
$ 5.X1 : num -0.295 -1.255 1.395 -1.985 -1.71 ...
$ 5.X2 : num 1.141 1.177 -1.003 -0.29 -0.234 ...
$ 6.X1 : num -0.0548 1.8673 -1.5388 -1.1063 0.3923 ...
$ 6.X2 : num -1.399 0.57 0.367 -0.811 -2.434 ...
$ 7.X1 : num 0.389 -1.058 0.61 1.102 -0.063 ...
$ 7.X2 : num 0.854 1.251 1.095 -0.485 0.451 ...
$ 8.X1 : num -2.018 0.849 0.3 0.988 -1.993 ...
$ 8.X2 : num -1.23 -1.025 -0.546 1.674 0.588 ...
$ 9.X1 : num 0.814 0.726 1.04 0.985 1.781 ...
$ 9.X2 : num -1.094 -1.051 0.749 1.426 0.402 ...
$ 10.X1: num 0.3786 1.6131 -0.4149 0.0684 -0.815 ...
$ 10.X2: num 0.383 -0.136 -0.751 -0.164 0.434 ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With