1

I have a list of dataframes. I'm trying to use lapply to produce a plot for each dataframe, with the dataframe's name as the plot title.

For example, this works, without the plot title:

# example dataframes
df1=data.frame(a=c(1,2,3,4,5),b=c(5,4,3,2,1))
df2=data.frame(a=c(2,2,2,2,2),b=c(5,4,3,2,1))

# list of dataframes
dflist=list(df1,df2)

# set dataframe names
names(dflist)=c("df1","df2")

# plotting area
par(mfrow=c(1,2))

# plots
lapply(dflist, function(x) {
a<-x[,"a"]
b<-x[,"b"]
plot(b,a)
x})

To get the list element name, I had hoped that the answer would be something simple like:

lapply(dflist, function(x) {
a<-x[,"a"]
b<-x[,"b"]
plot(b,a,main=names(x))
x})

But that gets the names of the variables within each dataframe.

I realise the answer is contained in here somewhere:

How to get the name of each element of a list using lapply()?

But I've had no luck trying to apply the solution to my specific case.

Ant Dancer
  • 11
  • 3
  • 5
    `lapply(names(dflist), function(nm) { x <- dflist[[nm]]; ...})` is one way. Another: `mapply(function(x, nm) { ... }, dflist, names(dflist), SIMPLIFY=FALSE)` is another. But since you're plotting (where side-effect is the intent and the return value might not be that critical), do you need to `*apply`? A `for` loop is just as fast (for this use) and might be clearer. – r2evans Nov 19 '18 at 16:45
  • @r2evans Thanks, I managed to apply both methods succesfully. I guess not - I was experimenting with having fewer `for` loops in my code, but perhaps this was the wrong place to start. – Ant Dancer Nov 20 '18 at 08:27

0 Answers0