Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
479 views
in Technique[技术] by (71.8m points)

r - List of plots using lapply

I have been using lapply and sapply as my go-to functions recently. So far so good, but why the following code does not work baffles me.

df<-as.data.frame(matrix(rnorm(50),ncol=5))
names(df)<-c("x1","x2","x3","x4","x5")
df1<-seq_len(10)

ll<-lapply(seq(1,5), function(i) qplot(df1,df[,i]))

I get the error:

Error in `[.data.frame`(df, , i) : undefined columns selected

Ok, apparently I made quite an unfortunate mistake in my reproducible code. It works now, but all the plots in the ll list are the same plot. When I run this:

do.call(grid.arrange,ll)

I get the following image:

Grid

All the plots are the same! This is also the output I get when I run this through my data.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There are problems with lazy evaluation, or something like it anyway. You need to do the following:

ll<-lapply(
  seq(1,5), 
  function(i) qplot(data=data.frame(y=df[, i]), df1, y)
)

This will force the y values to be updated for each plot.

More discussion in this other SO Post.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...