recharts4r

How to dynamically pass column name in e_bar (echarts4r) function?


I have a dataframe which contains count for each continent year wise. Below is the dataframe.

# A tibble: 4 x 4
  continent year_2020 year_2021 year_2022
  <chr>         <dbl>     <dbl>     <dbl>
1 Asia             35       177       350
2 Europe           45        47        84
3 Australia        26        46        58
4 Africa           15        20        25

And this is the R script I used to create the graph

stack %>%
  e_charts(continent) %>%
  e_bar(year_2020) %>%
  e_bar(year_2021) %>%
  e_bar(year_2022)

Graph:

enter image description here

My expectation is how do I pass this column names dynamically. The above dataframe is sample dataset and the year column keeps on increasing. My idea is to show max of 3 bars per continent.

What I tried was, have a start year and end year so the bar graph can be shown based on the input and not hotcode the column name in e_bar function.

start_year <- "2020"
end_year <- "2022"
year_val <- paste0("year_",start_year:end_year)
  
  year_val1 <- year_val[1] 
  year_val2 <- year_val[2] 
  year_val3 <- year_val[3] 

stack %>%
  e_charts(continent) %>%
  e_bar(sym(year_val1)) %>%
  e_bar(sym(year_val2)) %>%
  e_bar(sym(year_val3))

But was getting the below error

Error in chr_as_locations():
! Can't subset columns that don't exist.
x Column sym(year_val1) doesn't exist.

Need help on how to dynamically to pass the year columns.


Solution

  • One option would be to switch to the "underscored" version of e_bar, i.e. e_bar_ which allows to pass the name of the series as a character string:

    library(echarts4r)
    
    stack |>
      e_charts(continent) |>
      e_bar_(year_val1) |>
      e_bar_(year_val2) |>
      e_bar_(year_val3)
    

    DATA

    stack <- structure(list(continent = c("Asia", "Europe", "Australia", "Africa"), year_2020 = c(35L, 45L, 26L, 15L), year_2021 = c(
      177L, 47L,
      46L, 20L
    ), year_2022 = c(350L, 84L, 58L, 25L)), class = "data.frame", row.names = c(
      "1",
      "2", "3", "4"
    ))