Search code examples
rdplyrr-leaflet

Creating leaflet.minicharts popup labels for many different plots


I am using R leaflet.minicharts to create plots for each of several input files. I would like to create custom labels for each of the pie charts or bar plots within each minichart plot, but am having trouble with the code.

I have a data frame (df) similar to the following:

    location grp1 grp2 grp3 grp4
1   loc1     1    0    0    0
2   loc2     0    5    0    1
3   loc3     1    0    3    0
4   loc4     0    2    2    2
5   loc5     0    1    0    7

And would like to create a popup label for each pie chart (or barplot) within each plot that follows this format:

loc1
grp1: 1
grp2: 0
grp3: 0
grp4: 0

Based on another post (Leaflet for R: Display several data rows in popup) I see that my label format should be as follows:

my_popups <- df %>%
   group_by(location) %>%
   mutate(popup = paste0("<h3>", location,
   paste("grp1:", grp1, "<b>", "grp2:", grp2, "<b>", "grp3:", grp3, "<b>", "grp4:", grp4, "<b>", collapse = "<br>"))) %>%
   pull(popup)

But how can I automate my_popups to generate custom labels for several different input files that will have varying levels for grp (e.g. grp1 through grp4 is shown here, but I also have inputs for grp1 through grp5, and so on). I don't want to manually enter the "paste" portion of this code for every input.

I've created a vector with a portion of my data frame column names as follows:

[1] "grp1"     "grp2"     "grp3"     "grp4" 

I'm thinking there should be a way to paste this in the correct format for my_popups, but am not quite sure how to proceed. Any tips will be helpful!


Solution

  • I think this could do the trick maybe, probable, surely, with some minor changes:

    cols <- colnames(df)     
    coln <- cols[grepl("grp", cols)]
    coln <- paste0("<b>",coln[2:length(coln)],":" )
    coln<-c(coln, "<b>")
    df$popup <- apply(df[,-1],1,paste,coln,collapse="") 
    df %>% mutate(popup = paste0("<h3>", location,"grp1:", popup))
    

    A few small tweaks to get the exact formatting @nrcombs wanted:

    cols <- colnames(df)     
    coln <- cols[grepl("grp", cols)]
    coln <- paste0("<br>",coln[2:length(coln)],": " )
    coln<-c(coln, "<br>")
    df$popup <- apply(df[,-1],1,paste,coln,collapse="") 
    df %>% mutate(popup = paste0("<h3>", location, "</h3><br>", "grp1: ", popup))