Reputation: 63984
I have the following lists of data frame:
d1 <- data.frame(y1=c(1,2,3),y2=c(4,5,6))
d2 <- data.frame(y1=c(3,2,1),y2=c(6,5,4))
df <- list(FOO=d1, BAR=d2)
Which looks like this:
> df
$FOO
y1 y2
1 1 4
2 2 5
3 3 6
$BAR
y1 y2
1 3 6
2 2 5
3 1 4
And a function that plot each individual data frame and named them based on list ID:
plot_df_func <- function(basename="QUX",in_df) {
outfile <- paste(basename,".png",sep="")
png(outfile)
plot(in_df,main=basename)
dev.off()
}
How can I use lapply
in this case?
At the end of the day it will have "FOO.png" and "BAR.png".
I tried this but failed:
> lapply(df, plot_df_func)
Error in plot(in_df, main = basename) :
argument "in_df" is missing, with no default
Upvotes: 2
Views: 78
Reputation: 132696
I would use a for
loop. In my opinion, a for
loop is always preferable if you want only side effects (like plots or files) and no return value.
d1 <- data.frame(y1=c(1,2,3),y2=c(4,5,6))
d2 <- data.frame(y1=c(3,2,1),y2=c(6,5,4))
df <- list(FOO=d1, BAR=d2)
plot_df_func <- function(basename="QUX",in_df) {
#outfile <- paste(basename,".png",sep="")
#png(outfile)
plot(in_df,main=basename)
#dev.off()
}
layout(1:2)
for (i in names(df)) plot_df_func(i, df[[i]])
Upvotes: 1