0

Firstly, I have a big data.frame which has 104 rows and 12 columns, I would like to split it up to 13 rows of 8 rows each with the 12 columns.

I am trying to make a code robust enough to not care how many rows there are but simple make a new data.frame every 8 rows.

Also, is it possible after this point to make a code which loops through the 13 data.frames for some calculations?

  • 6
    [See here](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) on making an R question that folks can help with. That includes a sample of data, all necessary code, and what you've tried. Do [this](https://stackoverflow.com/q/14164525/5325862), [this](https://stackoverflow.com/q/7060272/5325862) and [this](https://stackoverflow.com/q/3302356/5325862) post not help? – camille Feb 06 '20 at 18:32
  • 5
    `Map(function(x,y) write.csv(x,paste0("file",y,".csv"),rownames = FALSE),split(your_data, rep(1:13, each = 8, length = 104)),1:13)` – Onyambu Feb 06 '20 at 18:33
  • 2
    And of course, change that hard-coded `104` to `nrow(your_data)`, and you have a more general solution :-) – r2evans Feb 06 '20 at 18:48
  • An alternative to the `rep` that doesn't hard-code "13" is `(seq_len(nrow(your_data)) - 1) %/% 8` (to further generalize to the number of sets made, which is contingent on the size of the frame). – r2evans Feb 06 '20 at 18:51

1 Answers1

1

Here is a way using data.table.split

library(data.table)

#sample data
set.seed(123)
AA <- data.frame( data = rnorm(104) )

#set number of rows to split on
chunksize = 8
#split on create rowid's
l <- split( setDT(AA)[, rowID := (.I-1) %/% chunksize][], by = "rowID")
#names of the list will become the names of the data.frames
names(l) <- paste0( "df", names(l) )
#write the elements of the list to the global environment, using their names
list2env( l, envir = globalenv() )
Wimpel
  • 26,031
  • 1
  • 20
  • 37