0

I have the following array in R:

    1    2    3    4    5    6    7    8    9    10    11    12
A   0    0.7  0.9  0.8  0    0    0    0    0    0.1   0     0.1
B   0.1  0.1  0    0.2  0    0.2  0.1  0    0    0.2   0     0.4
C   0    0.4  0.1  0.3  0    0    0.4  0    0    0.3   0     0

I would like to make this array into one column using R code. But I want it to start from the odd columns, going row by row, then come back and do the even columns, row by row. So in this case by column would be ordered:

0, 0.9, 0, 0, 0, 0, (row A, columns 1,3,5,7,9,11) followed by 0.7, 0.8 and so on in one big column.

GR1818
  • 139
  • 1
  • 13
  • You can use recycling of a logical vector i.e. `c(TRUE, FALSE)` and opposite to subset the odd/even columns – talat Jul 03 '17 at 13:28

1 Answers1

0

If the array is a matrix m, then...

t(m)[c(seq(1,length(m),2),
       seq(2,length(m),2))]

 [1] 0.0 0.9 0.0 0.0 0.0 0.0 0.1 0.0 0.0 0.1 0.0 0.0 0.0 0.1
[15] 0.0 0.4 0.0 0.0 0.7 0.8 0.0 0.0 0.1 0.1 0.1 0.2 0.2 0.0
[29] 0.2 0.4 0.4 0.3 0.0 0.0 0.3 0.0

The above will only work if you have an even number of columns. In the more general case, this is probably better...

c(t(m[,c(TRUE,FALSE)]),t(m[,c(FALSE,TRUE)]))
Andrew Gustar
  • 17,295
  • 1
  • 22
  • 32