Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to slice data in lapply function

I want to arrange N ggplot (each one is facetted) on a grid with grid.arrange.

library(tidyverse)
library(ggplot2)
library(gridExtra)


plots <- lapply(unique(mtcars$cyl), function(cyl) {
    data <- mtcars %>% filter(cyl == cyl)
    ggplot(data, aes(x=mpg, y=hp))+
        geom_point(color = "blue")+
        facet_wrap(.~carb)}) %>% 
    do.call(grid.arrange, .)
do.call(grid.arrange, plots )

The problem is that all the plots are based on the entire dataset and they render the same plot, while they shuold be different as I filter them in line

data <- mtcars %>% filter(cyl == cyl).

like image 466
giannic Avatar asked May 23 '19 07:05

giannic


2 Answers

filter deals with cyl too letteral and treated as a string, therefore cyl==cyl is TRUE for the entire dataset. You can solve this by unquote cyl using !! or use another variable name in the function e.g. x.

#Option 1
data <- mtcars %>% filter(cyl == !!cyl)
#Option 2
... function(x) {
    data <- mtcars %>% filter(cyl == x)
...
like image 163
A. Suliman Avatar answered Nov 01 '22 17:11

A. Suliman


Here is a tidyverse approach

library(tidyverse)

group_plots <- mtcars %>%
                 group_split(cyl) %>%
                 map(~ggplot(., aes(x = mpg, y = hp))+
                 geom_point(color = "blue") +
                 facet_wrap(.~carb))

do.call(gridExtra::grid.arrange, group_plots)

enter image description here

like image 27
Ronak Shah Avatar answered Nov 01 '22 18:11

Ronak Shah