I have a 100 text files with matrices which I want to open using R - the read.table() command can be used for that. I cant figure out how to assign these files to separate variable names so that I can carry out operations on the matrices. I am trying to use the for loop but keep getting error messages. I hope somebody can help me out with this...
Asked
Active
Viewed 1,597 times
2
-
incidentally, the answer here might be helpful http://stackoverflow.com/questions/15593001/how-to-upload-a-folder-consisting-of-folders-in-r-for-windows-i-am-uploading-v/15593645#15593645 – Ricardo Saporta Mar 24 '13 at 04:09
2 Answers
2
If you have 100 files, it may make more sense to simply keep them in one neat list.
# Get the list of files
#----------------------------#
folder <- "path/to/files"
fileList <- dir(folder, recursive=TRUE) # grep through these, if you are not loading them all
# use platform appropriate separator
files <- paste(folder, fileList, sep=.Platform$file.sep)
# Read them in
#----------------------------#
myMatrices <- lapply(files, read.table)
Then access via, eg, myMatrices[[37]]
or using lapply

Ricardo Saporta
- 54,400
- 17
- 144
- 178
-
@user2203793, you need to use double-brackets. Take a look at the difference between `myMatricies[1]` and `myMatricies[[1]]`. The latter is a matrix and the former is a list containing only one element, that element is a matrix. `+` does not make sense for lists, but it does for matrices. – Ricardo Saporta Mar 24 '13 at 05:13
0
Would it be easer to just use list.files?
For example:
files <- list.files(directory/path, pattern= "regexp.if.needed")
And then you could access each element by calling files[1], files[2], etc. This would allow you to pull out either all the files in a directory, or just the ones that matched a regular expression.

SummerEla
- 1,902
- 3
- 26
- 43