I have a text file that has one colunm of 1800 entries that are actually two sets of data (size,age) that have been combined. The first number (row1,column1) is size 1, the second number (row2,column1) is age1, the third column (row3,column1) is size 2, the fourth number (row4,column1) is age2, and so on. Does anyone know how to split this into a matrix of two columns of 900 entries each?
Asked
Active
Viewed 1,870 times
0
-
I do! But I don't know what your data looks like or what you've tried so far... I'd start with `read.table` and `read.csv`, but if you can post some of said file, I could tell you for sure! – Justin Mar 01 '12 at 00:14
-
I had read the table into R using the read.table function, but was stymied at that time. The first few rows of the data look like this:121.4596925 8.268601722 115.2194678 6.273456593 148.9 16.8 117.7088225 8.19989356 271.5483869 96.45334797 – ScottAK Mar 01 '12 at 00:22
-
Then the answer MYaseen208 gave below should work. – Justin Mar 01 '12 at 00:29
3 Answers
2
Suppose you have data.frame
df. Then try this
Size <- df[seq(from = 1, to = nrow(df), by = 2), 1]
Age <- df[seq(from = 2, to = nrow(df), by = 2), 1]
dfNew <- data.frame(Size, Age)

MYaseen208
- 22,666
- 37
- 165
- 309
1
If you have a single vector x
containing your alternating size and age data:
df <- do.call(data.frame, split(x, c("size", "age")))
If you want 2-column matrix instead, use cbind
:
df <- do.call(cbind, split(x, c("size", "age")))
This isn't the most efficient way, but it does automatically give you column names for free.

Ryan C. Thompson
- 40,856
- 28
- 97
- 159
1
You can make a matrix out of it and do it that way.
matrix(DF[,1], ncol=2, byrow=TRUE)
where DF
is the data.frame you read the data into.

Brian Diggs
- 57,757
- 13
- 166
- 188