0

just a follow-up question from a previous thread, with previous help, using group_by and filter allowed me to only return countries that both have Import and Export values and view them separately. However, I realised now that I need to return rows based on an additional condition where the Species must also have fulfilled the Import & Export conditions.

For example, the string should only return rows belonging to country C as the species and country both meet the export & import condition. But I keep getting countries that fulfil the condition with species that do not meet the condition of having BOTH import and export.

Country Year Quantity Description Import/Export Species A 2001 10 Frozen Export X B 2001 50 Fresh Import X B 2004 20 Frozen Export Y C 2003 30 Frozen Import X C 2005 40 Fresh Export X C 2006 60 Frozen Import X D 2007 290 Fresh Import Y 

Heres the Data for testing:

structure(list(Country = c("A", "B", "B", "C", "C", "C", "D"), Year = c(2001, 2001, 2004, 2003, 2005, 2006, 2007), Quantity = c(10, 50, 20, 30, 40, 60, 290), Description = c("Frozen", "Fresh", "Frozen", "Frozen", "Fresh", "Frozen", "Fresh"), `Import/Export` = c("Export", "Import", "Export", "Import", "Export", "Import", "Import" ), Species = c("X", "X", "Y", "X", "X", "X", "Y")), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, -7L)) 
3
  • Link to previous thread: stackoverflow.com/questions/69143212/… Commented Sep 16, 2021 at 5:21
  • 1
    If you run the code in your post it returns only rows with Country = 'C'. what is your expected output ? Commented Sep 16, 2021 at 9:34
  • @RonakShah Hi Ronak! That was actually the expected output, It worked on the 2nd try when I restarted RStudio... not sure why but I guess it works now! Commented Sep 16, 2021 at 12:13

1 Answer 1

0

Grouping based on Country AND Species helped me get the answer, took a few tries but the dplyr string below works

df %>% group_by(Country,Species) %>% filter(all(c('Import', 'Export') %in% Import/Export)) %>% ungroup()

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.