Johann Kim
2011-Mar-09 22:56 UTC
[R] How can I manipulate a data.frame that is just created by assign() while still being in the loop?
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 Many thanks for help! Johann
Uwe Ligges
2011-Mar-10 09:29 UTC
[R] How can I manipulate a data.frame that is just created by assign() while still being in the loop?
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 loopI'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.