[R] How can I manipulate a data.frame that is just created by assign() while still being in the loop?

Uwe Ligges ligges at statistik.tu-dortmund.de
Thu Mar 10 10:29:27 CET 2011



On 09.03.2011 23:56, Johann Kim wrote:
> Hello everyone,
>
> I want to use a loop to load many files, each into a seperate variable (data.frames) and then
> - still in the loop - manipulate the present variable/data.frame.
>
> So far this works:
> for (i in 1:2){
> 	var<- paste("var",i,sep="")
> 	fileName<- paste(i,"rating.txt", sep="_")
> 	assign(var, read.table(fileName))
>
> But how can I now referr to var / var[i] to manipulate that data.frame?
> For example: var<- var[ , -1]
>
> } # end of the for loop

I'd suggest to generate a list of data.frames rather assigning them to 
objects of different names:


var <- vector(mode = "list", length = 2)
for (i in 1:2){
     fileName<- paste(i, "rating.txt", sep = "_")
     var[[i]] <- read.table(fileName)
     var[[i]] <- var[[i]][ , -1]
}

or maybe nicer for all files ending in "rating.txt":


files <- dir(pattern = "rating\\.txt$")
var <- vector(mode = "list", length = length(files))
for (i in seq_along(files)){
     var[[i]] <- read.table(files[i])
     var[[i]] <- var[[i]][ , -1]
}

Uwe Ligges





>
> Many thanks for help!
> Johann
> ______________________________________________
> 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