Emilio M. Bruna - 11 months ago 61

R Question

a questions from a relative n00b: I’d like to split a vector into three vectors of different lengths, with the values assigned to each vector at random. For example, I’d like to split the vector of length 12 below into vectors of length 2,3, and 7

I can get three equal sized vectors using this:

`test<-1:12`

split(test,sample(1:3))

Any suggestions on how to split test into vectors of 2,3, and 7 instead of three vectors of length 4?

Answer Source

You could use `rep`

to create the indices for each group and then split based on that

```
split(1:12, rep(1:3, c(2, 3, 7)))
```

If you wanted the items to be randomly assigned so that it's not just the first 2 items in the first vector, the next 3 items in the second vector, ..., you could just add call to `sample`

```
split(1:12, sample(rep(1:3, c(2, 3, 7))))
```

If you don't have the specific lengths (2,3,7) in mind but just don't want it to be equal length vectors every time then SimonO101's answer is the way to go.