[R] looping through data frames in a workspace

lucy b lucy.lists at gmail.com
Tue Mar 4 21:01:33 CET 2008


Thanks for helpful replies. Unfortunately, I didn't mention that I
want to overwrite the existing data frame with the corrected one using
the same name. Here's what I have:

## get names of data frames
frames <- names(Filter(function(x) x=="data.frame",
                   sapply(objects(),function(x)
                          class(eval(parse(text=x))))))
## loop through list
for( i in seq(along=frames) ) {

	#don't need next line, but good to remember if need to exclude a df
	#if (frames[i] != "junk") {

	df <- eval(parse(text=frames[i]))

	for (c in 1:ncol(df)){
		if (is.factor(df[,c])) {
			df[,c] <- gsub("\r\n","",as.vector(df[,c]))
			}
		}

	names(df) <- frames[i]

	}#end first if

}#end first for
#END

Unfortunately, the "names(df)<-frames[i]" line just changes the name
of the first column in df. How can I overwrite the existing data frame
using the right name?



More information about the R-help mailing list