Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

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!

like image 929
rnorberg Avatar asked Dec 27 '25 21:12

rnorberg


1 Answers

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))
like image 110
Aaron left Stack Overflow Avatar answered Dec 30 '25 15:12

Aaron left Stack Overflow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!