How to split the data 1 1 2 2 3 3 to 1 2 3 1 2 3 in R?

Viewed 85

I want to convert a vector:

1 1 2 2 3 3

to

1 2 3 1 2 3 

How to do it? Many thanks.

3 Answers

You can use a matrix to layout the original vector by rows and then convert it back to a vector to get the desired result.

v = c(1,1,2,2,3,3)

v2 = as.vector(matrix(v, nrow = length(unique(v)), byrow = T))

> v2
[1] 1 2 3 1 2 3

The length(unique(v)) is there to generalize how many rows the matrix should have and not hardcode a 3.

Another example:

v = c(1,1,1,2,2,2,3,3,3,4,4,4)
v2 = as.vector(matrix(v, nrow = length(unique(v)), byrow = T))

v2
[1] 1 2 3 4 1 2 3 4 1 2 3 4

We can use rbind/split

c(do.call(rbind, split(v1, v1)))
#[1] 1 2 3 1 2 3

Or if there are unequal number of replications of each element, get the order of the rowid

library(data.table)
v1[order(rowid(v1))]
#[1] 1 2 3 1 2 3

Or with base R

v1[order(ave(v1, v1, FUN = seq_along))]
#[1] 1 2 3 1 2 3

data

v1 <- c(1, 1, 2, 2, 3, 3)
vec <- c(1, 1, 2, 2, 3, 3)
rep(unique(vec), 2)

[1] 1 2 3 1 2 3
Related