# Reading random text file in R

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?

Thanks

-

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:

readLines(file)


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:
print(lisfil[i])
}

-
You need to shuffle listfil somewhere in your code. –  chl Jan 26 '11 at 8:17
@chl: I assumed that getting the filenames into a variable was his main question. –  bill_080 Jan 26 '11 at 16:15
Yes, I just re-read the question and it makes sense as filenames are assumed to follow no particular order. –  chl Jan 26 '11 at 18:33