I have about 500 text documents stored in a directory. I want to randomly select one to read in the contents (this process will be repeated several times). The names of the files are not sequential. By this I mean they are not named something like 1.txt, 2.txt, 3.txt,... The names are basically random characters.

How can I do this?



2 Answers 2


First, select one file randomly from the current directory:

file <- sample(list.files(), 1)

Then do whatever you want with it, e.g. read all lines:


If you want to repeat this several times, you could do it in one step:

readLines(sample(list.files(), 1))

Do a list.files and then access each file by its index.

 lisfil <- list.files("E:\\Data") #Replace E:\\Data with your directory name
 lenlisfil <- length(lisfil)
 for (i in 1:lenlisfil) {
    #Do something to the current file such as:
  • $\begingroup$ You need to shuffle listfil somewhere in your code. $\endgroup$
    – chl
    Commented Jan 26, 2011 at 8:17
  • $\begingroup$ @chl: I assumed that getting the filenames into a variable was his main question. $\endgroup$
    – bill_080
    Commented Jan 26, 2011 at 16:15
  • $\begingroup$ Yes, I just re-read the question and it makes sense as filenames are assumed to follow no particular order. $\endgroup$
    – chl
    Commented Jan 26, 2011 at 18:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.