user319487
user319487

Reputation:

In R, how can I loop over data frames?

I'm working with several data frames with names following this structure:

data.bzk.18
data.bzk.19
data.bzk.20
data.bzk.21

I'd like to use plyr to summarize data and basically run the following on each of the data frames:

bzk.tot.18 <- plyr::count(data.bzk.18, c("BZNR"))

I wanted to put loop over all of them and came up with solution like that

for(i in 18:21) {
  to <- paste("bzk.tot", i, sep = ".")
  assign(to, i)

  from <- paste("data.bzk", i, sep = ".")
  assign(from, i)

  to <- plyr::count(from, c("BZNR")) #totals
}

Unfortunately it doesn't work. Where have I done mistake?

Upvotes: 0

Views: 207

Answers (1)

Ricardo Saporta
Ricardo Saporta

Reputation: 55340

the short answer is that instead of:

   to <- plyr::count(from, c("BZNR")) #totals

use:

    assign(to, plyr::count(get(from), c("BZNR")) )

and get rid of the previous assign statements.


the long answer is that you probably do not want to go about it such a fashion. Better to collect all of your data.frames into a list and iterate over the list instead.

Upvotes: 3

Related Questions