Search code examples
rconditional-statementsmultiple-columnsnaaccount

the number of NAs per conditions


I have a long database df. and there are two columns city (10000 with NAs) and country (i have 250 countries). I want to know the number of NAs cities per country. I tried to do pivot wider and then colSums(is.na(df)) but is not working. Is there an other way?

many thanks Eleni


Solution

  • Without a reproducable dataset it is hard to say but using dpyr/tidyverse I'd do something like this:

    df %>%
       group_by(country) %>%
       summarise(count_na = sum(is.na(city)))