1

I have the names of a group of data frames given in the variable "dfs", as an array of Strings. I.e.

> dfs
"dfs1" "dfs2" ... "dfsk"

I want to rename the columns of each of the data frame in dfs. That means I want to apply a function 'func' to each of the entries in dfs and write the result back. I.e. the result should be equal to evaluating

dfs1 <- func(dfs1)
dfs2 <- func(dfs2)
...
dfsk <- func(dfsk)

The difficulty is, that dfs might be arbitrarily long and the content of dfs is only known at runtime.

I have tried to write a function func and apply it to dfs using:

lapply( mget(dfs), func)

However this leaves the actual data.frames unchanged.

My Question has similarities to the following unanswered Question:

Apply an already defined function to all dataframes at once

Community
  • 1
  • 1
MarvMind
  • 3,366
  • 2
  • 21
  • 19
  • Welcome to Stack Overflow. Please read [Stack Overflow: How to ask](http://stackoverflow.com/questions/how-to-ask) and [Jon Skeet's Question Checklist](http://msmvps.com/blogs/jon_skeet/archive/2012/11/24/stack-overflow-question-checklist.aspx) to find out how to ask a good question that will generate good useful, answers. – Our Man in Bananas Jul 07 '14 at 09:22
  • @David `func` changes colnames of each data.frame – MarvMind Jul 07 '14 at 10:55
  • Can you post some sample data sets and the `func` syntax into the question? – David Arenburg Jul 07 '14 at 10:57
  • @Philip: Which Point in http://msmvps.com/blogs/jon_skeet/archive/2012/11/24/stack-overflow-question-checklist.aspx should are you refering to? – MarvMind Jul 07 '14 at 10:59
  • In your example, just add `assign(dfs[1], mtcars)` – Remko Duursma Jul 07 '14 at 11:10
  • With your `apply` call the columns don't change, but you have a _single_ object that holds the changed data.frames. You can work on each element using `lapply`. Now isn't that neat? – Roman Luštrik Jul 07 '14 at 12:25

1 Answers1

0

In found a Solution: The key is to use eval instead of apply. The desired behavior can be obtained using:

cCmd  <- paste(dfs, "<- func(" ,dfs,")", sep="")
eCmd  <- parse(text=cCmd)
eval(eCmd)

This might not be the most elegant way, but it works.

MarvMind
  • 3,366
  • 2
  • 21
  • 19