List of sites using lapply

I use lapply and sapply as my go-to functions. So far so good, but why the following code does not work puzzles 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 an error message:

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

Well, apparently, I made a rather unfortunate mistake in my reproducible code. It works now, but all the graphs in the list llare the same plot. When I ran this:

do.call(grid.arrange,ll)

I get the following image:

Grid

All stories are the same! This is also the output that I get when I run it through my data.

+2
source share
3 answers

There are problems with lazy pricing or something like that. You need to do the following:

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

This will cause y values ​​to be updated for each graph.

SO Post.

+5

, , . , ll , grid.arrange. i, 5 , i lapply. , df, , .

, , , , @BrodieG. data.frame, df . force i.

. :


data.frame facet_wrap. facet_wrap, melt reshape2:

library(ggplot2)
library(reshape2)
df$xvalues = 1:10
df_melt = melt(df, id.vars = 'xvalues')
ggplot(df_melt, aes(x = xvalues, y = value)) + 
    geom_point() + facet_wrap(~ variable)

enter image description here

+4

You say that it executes for 10 columns, where you have only 5. This works:

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

Source: https://habr.com/ru/post/1530565/


All Articles