convert rows after column

I have csv file which reads like this

1        5
2        3
3        2  
4        6 
5        3
6        7
7        2 
8        1
9        1

What I want to do is to this:

1       5      4       6     7      2
2       3      5       3     8      1
3       2      6       7     9      1

i.e after every third row, I want a different column of the values side by side. Any advise?

Thanks a lot

Answers


a <- read.table(text = "1        5
 2        3
 3        2  
 4        6 
 5        3
 6        7
 7        2 
 8        1
 9        1")

(seq_len(nrow(a))-1) %/% 3
# [1] 0 0 0 1 1 1 2 2 2

split(a, (seq_len(nrow(a))-1) %/% 3)
# $`0`
  # V1 V2
# 1  1  5
# 2  2  3
# 3  3  2

# $`1`
  # V1 V2
# 4  4  6
# 5  5  3
# 6  6  7

# $`2`
  # V1 V2
# 7  7  2
# 8  8  1
# 9  9  1

do.call(cbind,split(a, (seq_len(nrow(a))-1) %/% 3))
#   0.V1 0.V2 1.V1 1.V2 2.V1 2.V2
# 1    1    5    4    6    7    2
# 2    2    3    5    3    8    1
# 3    3    2    6    7    9    1

Here's a way to do this with matrix indexing. It's a bit strange, but I find it interesting so I will post it.

You want an index matrix, with indices as follows. This gives the order of your data as a matrix (column-major order):

1, 1
2, 1
3, 1
1, 2
2, 2
3, 2
4, 1

...

8, 2
9, 2

This gives the pattern that you need to select the elements. Here's one approach to building such a matrix. Say that your data is in the object dat, a data frame or matrix:

m <- matrix(
        c(
           outer(rep(1:3, 2), seq(0,nrow(dat)-1,by=3), FUN='+'), 
           rep(rep(1:2, each=3), nrow(dat)/3)
        ),
        ncol=2
     )

The outer expression is the first column of the desired index matrix, and the rep expression is the second column. Now just index dat with this index matrix, and build a result matrix with three rows:

matrix(dat[m], nrow=3)
##      [,1] [,2] [,3] [,4] [,5] [,6]
## [1,]    1    5    4    6    7    2
## [2,]    2    3    5    3    8    1
## [3,]    3    2    6    7    9    1

Need Your Help

Indexing through a list in python

python list python-3.x for-loop enumerate

I have a list that I'm trying to loop through and index the number of each number in the list. The total list is around 1500-2000 numbers where each number represents subject behavior. I imported the

how to model mutually exclusive attributes in UML?

attributes uml mutual-exclusion

I'm working up an analysis model in UML, and I'm a bit stuck when trying to represent a constraint on a couple of attributes in a class diagram. In the following class: