-3

Given vector of N elements:

LETTERS[1:10]
[1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J"

How can one get a data.table/frame (df) as follows?

 >df
 one two
 A   B
 C   D
 E   F
 G   H
 I   J

EDIT

Generalizing I would like to know given a vector to split as follows:

   [A B C],[D E],[F G H I J] 

and obtaining:

     V1 V2 V3 V4 V5
      A  B  C NA NA
      D  E NA NA NA 
      F  G  H  I  J  
amonk
  • 1,769
  • 2
  • 18
  • 27
  • Please `dput` this `[A B C],[D E],[F G H I J] ` – Sotos Jul 05 '17 at 08:23
  • I mean split the LETTERS[1:10] in predefined positions – amonk Jul 05 '17 at 08:24
  • Ok, I get it. But how are your predefined positions structured? Is it a list with indices? a vector? a data frame? – Sotos Jul 05 '17 at 08:27
  • it is a predefined vector (given by a `grep` that seeks a specific pattern) – amonk Jul 05 '17 at 08:28
  • Ok. Please `dput` that vector for the example you shared – Sotos Jul 05 '17 at 08:29
  • For the sake of the example I would use `splitVec<-c(4,7)` the _positions_ of the LETTERS[1:10] than need to be split. Is it clearer now? – amonk Jul 05 '17 at 08:38
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/148381/discussion-between-amonk-and-sotos). – amonk Jul 05 '17 at 08:40
  • 1
    Maybe [this link](https://stackoverflow.com/questions/16357962/r-split-numeric-vector-at-position) will help. Some nice functions in there. – Sotos Jul 05 '17 at 08:50

1 Answers1

1

One option is the matrix way

as.data.frame(matrix(LETTERS[1:10], ncol=2,byrow=TRUE,
      dimnames = list(NULL, c('one', 'two'))), stringsAsFactors=FALSE)
#  one two
#1   A   B
#2   C   D
#3   E   F
#4   G   H
#5   I   J

f we need to create an index, we can use gl to split the vector and rbind

do.call(rbind, split(v1, as.integer(gl(length(v1), 2, length(v1)))))

where

v1 <- LETTERS[1:10]

Update

Based on the update in OP's post

lst <- split(v1, rep(1:3, c(3, 2, 5)))
do.call(rbind, lapply(lst, `length<-`, max(lengths(lst))))
#   [,1] [,2] [,3] [,4] [,5]
#1 "A"  "B"  "C"  NA   NA  
#2 "D"  "E"  NA   NA   NA  
#3 "F"  "G"  "H"  "I"  "J" 

Or otherwise

library(stringi)
stri_list2matrix(lst, byrow = TRUE)

Update2

If we are using a 'splitVec'

lst <- split(v1, cumsum(seq_along(v1) %in% splitVec))

and then proceed as above

akrun
  • 874,273
  • 37
  • 540
  • 662