2

I already have defined a function (which works fine). Nevertheless, I have 20 dataframes in the working space to which I want to lapply the same function (dat1 to dat20).

So far it looks like this:

dat1 <- func(dat=dat1)
dat2 <- func(dat=dat2)
dat3 <- func(dat=dat3) 
dat4 <- func(dat=dat4)
...
dat20 <- func(dat=dat20)

However, is there a way to do this more elegant with a shorter command, i.e. to lapply the function to all dataframes at once?

I tried this, but it didn't work:

mylist <- paste0("dat", 1:20, sep="")
lapply(mylist, func) 
Thomas
  • 43,637
  • 12
  • 109
  • 140
PLS
  • 21
  • 2

3 Answers3

1

Try something like:

lapply(mget(ls(pattern="dat")),func)

Some details: The pattern argument in ls will limit which object names it lists (e.g., I assume you have other objects including your function in the global environment). mget retrieves those objects from the environment and turns them into a list, which you can then lapply your function over.

Thomas
  • 43,637
  • 12
  • 109
  • 140
1

If you have the name of a variable, you can use get() to retrieve the value from the workspace. The corresponding assignment function is called assign():

mylist <- paste0("dat", 1:20)
lapply(mylist, function(name) assign(name, func(dat=get(name))) )
Ken Williams
  • 22,756
  • 10
  • 85
  • 147
1

The desired behavior can be obtained using eval instead of lapply.

Assume mylist to be the names of the data.frame you want to apply fun to. mylist might be generated using

mylist <- ls(pattern="dat")

Then you can use the following code to do exactly what you want:

cCmd  <- paste(mylist , "<- func(" ,mylist,")", sep="")
eCmd  <- parse(text=cCmd)
eval(eCmd)
MarvMind
  • 3,366
  • 2
  • 21
  • 19