rnorberg
rnorberg

Reputation: 482

Passing multiple objects into a function via sapply() or lapply() while maintaining the functionality of substitute() inside the function

My code is as follows:

x<-read.table('1')
y<-read.table('2')
z<-read.table('2')

MyFunc<-function (data){
  plot(data[1]~data[2])
  title(main=substitute(data))
  data.new <- some.manipulations(data)
  write.csv(data.new,file=paste(substitute(data),".csv",sep=""))
}

my.list <- list(x,y,z)
lapply(mylist,MyFunc)

I want this to generate a graph and a .csv file for 25 or so different tables. It works fine if I call it individually - for example if I execute:

MyFunc(x)

I get a graph titled "x" and a file x.csv My problem is I need to do this many times, and when I put all of my tables in a list and try using lapply or sapply, each table somehow loses it's name so the graph has no title and the file isn't created because blank.csv isn't a viable file name. I also tried concatenating the objects:

my.list <- c(x,y,z)

This yielded the same issue. Any help would be much appreciated!

Upvotes: 3

Views: 1996

Answers (1)

Aaron - mostly inactive
Aaron - mostly inactive

Reputation: 37824

The usual way of handling something like this is to send the desired name to the function as well. In this case it may help to name the elements in your list with the desired names. Perhaps something like this:

f <- c('1', '2', '3')
d <- lapply(f, read.table)
names(d) <- f # optionally some other names

MyFunc <- function(dat, nam) {
  plot(dat[1]~dat[2])
  title(main=nam)
  dat.new <- some.manipulations(dat)
  write.csv(dat.new, file=paste(nam, ".csv", sep=""))
}

lapply(names(d), function(n) MyFunc(d[[n]], n))

Upvotes: 3

Related Questions