Using filter function from tidyverse library

Please help me my filter function on tidyverse does not recognize the variable I tried to use for filtering please advise. I keep on getting the message You can override using the .groups argument and theError in View : object 'Imports' not found. However, I do have the Imports variable after spreading the tradetype to a numeric variable cv.

Code:
poultry %>%
group_by( Year,
CountryofDestination,
CountryOfOrigin,
TradeType) %>%
summarise(
n = n(),
cv = sum(CustomsValue, na.rm = T)
) %>%
arrange(-n) %>%
spread(TradeType, cv) %>%
filter(Imports == '')

Could you run just this part of the code and share a screenshot?

If the value of tradeType is not exactly "Imports", but , for example "imports", I'd expect to see

! object 'Imports' not found

Another problem you have is that spread will never produce a columns where the value of imports is '', but either a value or NA, so you need to use ilter(is.na(Imports)).

Here's an example that prints out the dataframe after spread().


library(tidyverse)

poultry <- tribble(
  ~Year, ~CountryofDestination, ~CountryOfOrigin, ~TradeType, ~CustomsValue,
  2022, "USA", "Canada", "Exports", 1000,
  2023, "Canada", "USA", "imports", 2000, 
  2024, "USA", "Canada", "imports", 3000, 
)

poultry %>%
  group_by( Year,
    CountryofDestination,
    CountryOfOrigin,
    TradeType) %>%
  summarise(
    n = n(),
    cv = sum(CustomsValue, na.rm = T)
  ) %>%
  arrange(-n) %>%
  spread(TradeType, cv) %T>% print() %>% 
  filter(is.na(Imports))

Hi @Peter.123, maybe you has a problem with the columns names.

For check the columns names, use this:

names(poultry)

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.