2

I have a 1D array with an odd number of rows, 2435 rows. I want to split the array into smaller arrays and each time perform a small test.

Firstly, I want to split the big array into two smaller arrays.

Then I would like to split my array into 4 smaller arrays, then into 8 small arrays and so on.

Can anyone help with that?

An example is the following:

A<-1:2435

A1 1,2,3,4,...,1237

A2 1238, 1239,...,2435

Thanks in advance

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Gina
  • 157
  • 1
  • 8
  • not very clear what you want. Please try to add a [small example](https://stackoverflow.com/help/mcve) . Also, you can look at this [similar question](https://stackoverflow.com/questions/3318333/split-a-vector-into-chunks-in-r) – Aramis7d Jul 07 '17 at 13:55
  • I've seen that post but I think this one it just split the data. Can I store them after I had split them? – Gina Jul 07 '17 at 14:00
  • try to store them into a `list` – BENY Jul 07 '17 at 14:02
  • @Gina you can try something like `x <- 1:10; n = 3; x1 <- split(x, sort(x%%n))` and `x1` will have the splits. Then you can access them by `x1[[i]]` for the `i-th` part. – Aramis7d Jul 07 '17 at 14:07
  • Thanks, I did store them using the list function. I've never code in R so all these are new for me. Thanks for the help. – Gina Jul 07 '17 at 14:08

2 Answers2

0

Why not simply use the split() function? For example (using an odd length will return warnings but that's fine):

split(x = 1:11, f = 1:2) # to split into 2 distinct list elements
#$`1`
#[1]  1  3  5  7  9 11
#
#$`2`
#[1]  2  4  6  8 10

split(x = 1:11, f = 1:4)
#$`1`
#[1] 1 5 9
#
#$`2`
#[1]  2  6 10
#
#$`3`
#[1]  3  7 11
#
#$`4`
#[1] 4 8

And if you are really keen on splitting to 2, and then again by 2, you can always use the lapply() function which works on each element of a list:

lapply(split(x = 1:11, f = 1:2), split, f = 1:2)
#$`1`
#$`1`$`1`
#[1] 1 5 9
#
#$`1`$`2`
#[1]  3  7 11
#
#
#$`2`
#$`2`$`1`
#[1]  2  6 10
#
#$`2`$`2`
#[1] 4 8

The nested structure is a little bit of a pain but there are other methods for dealing with that, for example:

L <- split(x = 1:11, f = 1:2) # the main (first) split
names(L) <- letters[1:length(L)] # names the main split a and b
LL <- lapply(L, split, f = 1:2) # split the main split
unlist(LL, recursive = F)
#$a.1
#[1] 1 5 9
#
#$a.2
#[1]  3  7 11
#
#$b.1
#[1]  2  6 10
#
#$b.2
#[1] 4 8
Evan Friedland
  • 3,062
  • 1
  • 11
  • 25
0

If you want to split the data through the middle of the array, you can also use the split function:

a <- 1:2435

divide <- function(x, n = 2)
{
  i <- ceiling(length(x)/n)
  split(x,x%/%i+1)

}

divide(a)

and with more parts you can use

divide(a, n = 4)

Or in two itterations use

lapply(divide(a,2),function(x) divide(x,2))

With a higher value of n, the sizes will not be equal anymore, due to rounding issues. Which warrants the use of the nested approach.

Wietze314
  • 5,942
  • 2
  • 21
  • 40