[R] Index alternative to nasty FOR loop?

Charles C. Berry cberry at tajo.ucsd.edu
Wed Aug 6 20:10:56 CEST 2008


On Wed, 6 Aug 2008, zack holden wrote:

>
> Dear R wizards,
>
> I have a folder containing 1000 files. For each file, I need to extract the first row of each file, paste it to a new file, then write out that file. Then I need to repeat this operation for each additional row (row 2, then row 3, etc) for 23 rows in each file.
>
> I can do this with a for loop (as below).


This is surprising!

Can you give us an example where this actually works???

>
> Is there a way to use some of the indexing power of R to get around this nasty loop?
>
> Thank you in advance for any suggestions
>
> ###################
> newoutfile <- data.frame()
> list <- list.files("c:/data")

Bad practive to use 'list' as a variable name!


>
> file = 1

Above seems superfluous in view of the next line

> for(file in list) {
>   row <- file[1, ]

This doesn't really work, does it?

Where was dim(file) assigned?

>   newoutfile <- rbind(row, newoutfile)

Since 'newoutfile' was not intialized the above should have thrown an 
error.

>   file = file + 1

Ought to have thrown an error like

 	"non-numeric argument to binary operator"

when trying to execute the line above.

> write.csv(outfile, file = "output.csv")
> }
> ####################


You were asked to:

 	PLEASE do read the posting guide
 	http://www.R-project.org/posting-guide.html
 	and provide commented, minimal, self-contained, reproducible code.


Chuck

p.s. As you describe the problem, something like this should do

res <- sapply( list.files("c:/data",full=TRUE), readLines )

for ( i in seq(nrow(res) ) ){
 	write.csv( res[i,],
 		file=paste("row",i,"csv",sep='.'))
}


>
>
>
> 	[[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.
>

Charles C. Berry                            (858) 534-2098
                                             Dept of Family/Preventive Medicine
E mailto:cberry at tajo.ucsd.edu	            UC San Diego
http://famprevmed.ucsd.edu/faculty/cberry/  La Jolla, San Diego 92093-0901



More information about the R-help mailing list