Search code examples
rsortablejs

How do I initialize a bucket_list with dynamic data in R?


I would like to initialize a bucket_list in R with data from a dataframe. Let's assume I got the following data:

buckets <- data.frame(
  text=c("A","A","B"),
  labels=c(1,2,3)
)

Then I would like to achieve the following bucket_list:

library(sortable)
bucket_list(
  header="Test"
  ,add_rank_list(text = "A",labels = c(1,2))
  ,add_rank_list(text = "B",labels = c(1) )
)

My problem is that the contents of the dataframe buckets are dynamic, so I need a solution that takes the dataframe buckets as input.

Thank you very much in advance for your help!


Solution

  • You can convert your data.frame to a grouped list. Then, use lapply for each group and add_rank_list to put each list element into format needed for bucket_list.

    library(sortable)
    
    buckets <- data.frame(
      text=c("A","A","B"),
      labels=c(1,2,3)
    )
    
    blst <- split(buckets$labels, buckets$text)
    
    rlst <- lapply(names(blst), function(x) {
      add_rank_list(
        text = x,
        label = blst[[x]]
      )
    })
    
    do.call(bucket_list, c(header = "New Test Here", rlst))