How to split a vector into n vectors and print them in one table in R?

I want to split a vector, for example:

x<-c(1,2,3,4,5,6,7,8,9,10)

let n=2
   m=c(4,6)
y<-split(x,rep(1:n,m))

I need to print y as a table like:

y1 y2
1  5
2  6
3  7
4  8
  9
  10

How to print y with different rows? Many thanks.

3 answers

  • answered 2020-06-27 04:00 Ronak Shah

    You cannot have a dataframe/matrix of unequal length in R, you can append NA's to vector with shorter length.

    sapply(y, `[`, seq_len(max(lengths(y))))
    
    #      1  2
    #[1,]  1  5
    #[2,]  2  6
    #[3,]  3  7
    #[4,]  4  8
    #[5,] NA  9
    #[6,] NA 10
    

  • answered 2020-06-27 04:06 akrun

    We can use stri_list2matrix from stringi

    library(stringi)
    y1 <- stri_list2matrix(y)
    

  • answered 2020-06-27 04:11 A5C1D2H2I1M1N2O1R2T1

    Instead of splitting the data in the first place, you can consider a matrix and use matrix indexing to insert the values at the relevant positions. It's very fast.

    M <- matrix(NA, ncol = 2, nrow = max(m))
    M[cbind(sequence(m), rep(seq_along(m), m))] <- x
    M
    #      [,1] [,2]
    # [1,]    1    5
    # [2,]    2    6
    # [3,]    3    7
    # [4,]    4    8
    # [5,]   NA    9
    # [6,]   NA   10