-2

I have a dataframe with 2000 rows. I only wish to save 99 rows at a time into a csv file. Is it possible to write multiple csv files with 99 consecutive rows of the dataframe i.e 20 files of 99 rows for 1980 rows, and final csv file containing 20 rows?

Furthermore, given the amount of files created, is it possible to add _1, _2,_3 etc.. to the filename output to ensure they're easily defined?

zx8754
  • 52,746
  • 12
  • 114
  • 209
  • 1
    Welcome to Stackoverflow. Thank you for telling us this, please let us know if you need help fixing any code you might have issues with. – Gerhard Nov 06 '19 at 11:29
  • Related post: https://stackoverflow.com/q/3318333/680068 – zx8754 Nov 06 '19 at 11:54

1 Answers1

2

This should work

library( data.table )
#create sample data    
dt = data.table( 1:2000 )
#split dt into a list, based on (f = ) the integer division (+ 1) of the 'rownumbers' 
# by the preferred chuncksize  (99)
# use keep.by = TRUE to keep the integer division (+ 1) result 
# for naming the files when saving
l <- split( dt, f = dt[, .I] %/% 99 + 1, keep.by = TRUE )
#simple for loop, writing each list element, using it's name in the filename
for (i in 1:length(l)) {
  write.csv( data.frame( l[[i]]), file = paste0( "./testfile_", names(l[i]), ".csv" ) )
}

results in
enter image description here

Wimpel
  • 26,031
  • 1
  • 20
  • 37