1

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.

Michale
  • 131
  • 6

3 Answers3

4

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
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
3

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
A5C1D2H2I1M1N2O1R2T1
  • 190,393
  • 28
  • 405
  • 485
1

We can use stri_list2matrix from stringi

library(stringi)
y1 <- stri_list2matrix(y)
akrun
  • 874,273
  • 37
  • 540
  • 662