[R] Indexing within scan

Peter Dalgaard p.dalgaard at biostat.ku.dk
Wed Jul 20 00:22:35 CEST 2005


"Justin Rhodes" <rhodesju at ohsu.edu> writes:

> Dear R-help subscribers,
> 
> Can some one please help me figure out how to write code that will allow me to use a for loop to scan a number of files one by one, and then save a summary of each file as the for loop progresses.  For example I have 24 files named a1 through a24, and I want to do something like:
> 
> 
> results<-numeric(24)
> for (i in 1:24)
> {
>  
> p<-scan("ai.txt")  # where the i is an index for each of the 24 files
> 
> results[i]<-mean(p)
> }
> 
> Thanks for any help,
> 

paste("a", i, ".txt", sep="") 

should get you in the right direction. However, I don't think you
*really* want a for loop. Use vectorization and sapply instead:

names <- paste("a", 1:24, ".txt", sep="")
results <- sapply(names, function(n) mean(scan(n)) )

-- 
   O__  ---- Peter Dalgaard             Øster Farimagsgade 5, Entr.B
  c/ /'_ --- Dept. of Biostatistics     PO Box 2099, 1014 Cph. K
 (*) \(*) -- University of Copenhagen   Denmark          Ph:  (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)                  FAX: (+45) 35327907




More information about the R-help mailing list