I have a long column with lots of results from an analysis (as an .txt file, that I will read with R). Starting from the top, the first 5 rows are results that correspond to Sample1, the second chunk of 5 rows (rows 6, 7, 8, 9 and 10) correspond to Sample2, and so on from Sample1 to Sample57. So, I want to split that long column into 57 columns, to separate by sample. Let's start with a smaller example to simplify the problem, just using the first two samples (so, the column has only 10 values, 5 for each). Let's say we have this column vector:
0.01
0.02
0.45
0.34
0.55
0.78
0.08
0.49
0.50
0.33
And I know the first 5 numbers correspond to Sample1, and the second to Sample2. I want to do this:
0.01 0.78
0.02 0.08
0.45 0.49
0.34 0.50
0.55 0.33
Overall, I want to transform that columnar vector into a matrix where each column is 5 rows long, and those numbers are in the same order as they were in the original vector. It's like if you had cut the original vector into 5row-long pieces, and paste them on the right in order. I've searched commands to split one column into multiple columns, but they used things that recognized character patterns. This is a different scenario. Also I found this regarding the terminal Put every N rows of input into a new column , but I was wondering if there is a way in R to do that, and maybe also simpler.
Is there a way to do this strictly every 5 rows?
yes you can do following:
as.data.frame(split(data, 1:x))
where x = nr of rows / 5; in your example x = 2 as you have 10 observations
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