[R] Iteration through a list in R

MacQueen, Don macqueen1 at llnl.gov
Fri Mar 1 20:48:37 CET 2013


I suppose you have your filenames stored in a character vector, which I
will name "myfiles". (Within R, it is not a "list"; lists have a special
structure).

There is no such thing as a "tab separated matrix" in R. "tab separated"
would refer to the file, I presume.

for (nm in myfiles) {

  tmpdat <- read.table(nm, ## put appropriate arguments here )

  tmpmat <- as.matrix(tmpdat)
   ## might or might give you what you want,
   ## depending on what is in the files

  ## it might make sense to use scan() instead, depending on how
  ## your text files are structured.

  ## do whatever with tmpdat or tmpmat

}

When the loop is done, however, tmpdat and tmpmat will have only the
values from the last file. Saving all of them for later use is a different
question.

Often, you will get better help from r-help if you show what you have
tried, by which I mean showing some R code. As much as possible, using
examples that other people can run for themselves. (See the posting guide)

Hope this helps

-Don

-- 
Don MacQueen

Lawrence Livermore National Laboratory
7000 East Ave., L-627
Livermore, CA 94550
925-423-1062





On 2/28/13 4:30 AM, "Sahana Srinivasan" <sahanasrinivasan.91 at gmail.com>
wrote:

Hello :)
I'm just starting out with R and would appreciate your help with a couple
of problems I am running into.
I have used Sys.glob to get a list of all filenames having a particular
file extension (in my case, *.txt)
I would now like to use this list in the following manner: I would like to
use each filename from the list and open that file into a tab separated
matrix and proceed.
How can I go about iterating through each filename in the list and then
opening each of the files?
I believe as.matrix can be used to open the txt file as a table, is that
correct?

I know these are beginner queries but I would love your help. Thank you in
advance :)

	[[alternative HTML version deleted]]

______________________________________________
R-help at r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide
http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list