0

I am looking to make four graphs in ggplot each containing 7 data-series each of which is marked as a group in my data frame. I therefore need a way to filter my single long data frame by the 7 group keys. I want my code to work something like this:

library(tidyverse)

df <- mtcars[0:2]

df <- tibble::rownames_to_column(df, "groups")

grouped_df <- df %>% group_by(groups)

conditions = group_keys(grouped_df)[[1]]

subplot_1_data <- grouped_df %>%  filter(groups == AMC Javelin) ## this works
subplot_2_data <- grouped_df %>%  filter(conditions[6:10]) ##does not work
subplot_3_data <- grouped_df %>%  filter(groups == conditions[11:15]) ## does not work

i want to generate three ggplot graphs 1 with subplot_1_data and another with subplot_2_data and a third with subplot_3_data

I am struggling to achieve this. any hint on how to get multiple groups into 1 dataframe for plotting would be appreciated.

  • 2
    What is `otsa` defined as? Your code is unreproducible, it would help to have sample data for all variables you are using here. (More the point, `i <- "otsa"; filter(..., group==i)` is different than `filter(..., group==otsa)`.) – r2evans Mar 12 '20 at 16:07
  • Why are you trying to split your dataframe up - there are probably better solutions. If you really want to do this, you need `{{i}}` - dplyr uses non-standard evaluation - or use `split` – Richard Telford Mar 12 '20 at 16:08
  • 1
    why not just use simple `split` using `od_dfs <- split(OD.long.summarized, factor(group))`, – PKumar Mar 12 '20 at 16:09
  • I see you've added more code to the question --thank you. But to get a better answer (and the question reopened), I suggest reading and incorporating elements from [How to make a great R reproducible example?](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). Especially the aspects of using `dput()` for the input and then an explicit example of your expected dataset? – wibeasley Mar 12 '20 at 18:56

1 Answers1

1

What you are looking for is x %in% c("a", "b") instead of == when filtering using a vector.

library(tidyverse)

df <- mtcars[0:2] %>% 
  tibble::rownames_to_column("groups") %>% 
  group_by(groups)

conditions <- group_keys(grouped_df)$groups

subplot_1_data <- df %>% filter(groups == "AMC Javelin")
subplot_2_data <- df %>% filter(groups %in% conditions[6:10])
subplot_3_data <- df %>% filter(groups %in% conditions[11:15])
knytt
  • 583
  • 5
  • 15