3

I have question about how to generate random numbers for each .txt file generated by write.table command. I want to write different rows of random numbers to each .txt file.

ref_file <- data.frame(id=seq(1:10)) #

This creates 10 output file with random samples

lapply(seq_along(ref_file$id), function(i) write.table(sample(10,replace=F),paste0(ref_file$id[i],'.txt'), quote=FALSE, col.names = FALSE,row.names=FALSE))

My question is how to put different number of rows for each .txt file. For example 1.txt contains 3 rows of sample numbers but 10.txt can contain 6 random sample numbers.

Thanks in advance!

Alexander
  • 4,527
  • 5
  • 51
  • 98
  • Just as quick thought, wouldn't it be possible to change `sample(10)` to `sample(sample(10)[1])`? If I understood you correct that would create samples with different lengths between 1 and 10. – Daniel Fischer Dec 11 '15 at 12:58
  • @DanielFischer Thanks for comment. Now just creating one number for each .txt. I need different lengths for each .txt. – Alexander Dec 11 '15 at 13:04

1 Answers1

2

Maybe as stand alone function.

writeFiles <- function(n, maxRows=100){
  lapply(1:n,function(x) write.table(sample(sample(maxRows)[1],replace=F),paste(x,'.txt',sep=""), quote=FALSE, col.names = FALSE,row.names=FALSE))
}

writeFiles(3,10)

n defines the number of files and maxRows the maximum number of rows (And the numbers are then a unique subset of random length of 1:maxRows.

Daniel Fischer
  • 3,280
  • 1
  • 18
  • 29