count list of variables

Hi,

I'm interested in counting a list of variables similar to this:

library(gapminder)
gapminder %>%
  count(country)


gapminder %>%
  count(continent)


gapminder %>%
  count(year)

I tried using map in order to perform a loop using purrr, but I failed.

library(gapminder)
gapminder %>%
  select(country:year) %>%
  map(count)

The code below does work, but I would prefer to perform the task using count or group_by and count in order to gain expertise.

library(gapminder)
gapminder %>%
  select(country:year) %>%
  map(table)

Thank you!

This can't be the best way but it works.

library(tidyverse)
library(gapminder)
#> Warning: package 'gapminder' was built under R version 4.2.3
map(c("country","continent","year"), as.name) |> 
  map(.f = \(Nm)  count(gapminder,{{Nm}}))
#> [[1]]
#> # A tibble: 142 × 2
#>    country         n
#>    <fct>       <int>
#>  1 Afghanistan    12
#>  2 Albania        12
#>  3 Algeria        12
#>  4 Angola         12
#>  5 Argentina      12
#>  6 Australia      12
#>  7 Austria        12
#>  8 Bahrain        12
#>  9 Bangladesh     12
#> 10 Belgium        12
#> # … with 132 more rows
#> 
#> [[2]]
#> # A tibble: 5 × 2
#>   continent     n
#>   <fct>     <int>
#> 1 Africa      624
#> 2 Americas    300
#> 3 Asia        396
#> 4 Europe      360
#> 5 Oceania      24
#> 
#> [[3]]
#> # A tibble: 12 × 2
#>     year     n
#>    <int> <int>
#>  1  1952   142
#>  2  1957   142
#>  3  1962   142
#>  4  1967   142
#>  5  1972   142
#>  6  1977   142
#>  7  1982   142
#>  8  1987   142
#>  9  1992   142
#> 10  1997   142
#> 11  2002   142
#> 12  2007   142

Created on 2023-05-10 with reprex v2.0.2
It seems the problem with your version is that map(), as it iterates over a tibble, sends just the column to the function, not a tibble consisting of one column. The count() function expects a data frame as its first argument. When it gets factor, it throws and error.

Thanks for your answer.
You refer to the error I created with R has a bug, right?
Its a kind of flaw in the map syntax?

The closest I got to this style of approach was :

library(gapminder)
library(tidyverse)

gapminder %>%
  select(country:year) %>%
  imap(\(x,y){enframe(x=x,
                      value = y,
                      name=NULL) |> count(!!sym(y))})

but I much prefer this concise approach


map(names(gapminder)[1:3],
    \(x)count(gapminder,!!sym(x)))

This topic was automatically closed 21 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.