What do you want to do with the data in the list of files? Greg's answer shows you one way to read a single file, which you could stick in a loop over the file names. But do you want the results in n R objects or combined in some manner?
For example, I have two files foo.txt and bar.txt in my working directory. I can list all *.txt
files using list.files()
, then operate on that list to read them in and combine them in different ways.
For example: here we combine them into a matrix:
flist <- list.files(pattern = ".txt$") ## so we get only files .txt not .txt~
(f <- sapply(flist, scan))
## or to a data.frame
(df <- data.frame(sapply(flist, scan)))
## fix up the colnames and rownames
colnames(f) <- colnames(df) <- paste("File", seq_along(flist), sep = "")
head(df)
File1 File2
1 12 12
2 23 23
3 34 34
4 45 45
5 6 6
6 67 67
If you wanted to concatenate the files together into one long vector, then we could achieve that with
> do.call(c, lapply(flist, scan))
Read 10 items
Read 10 items
[1] 12 23 34 45 6 67 78 54 34 324 12 23 34 45 6 67 78 54 34
[20] 324
HTH