0

For some background, I am creating a plot in R that has a dropdown-style filter, and to create the filter I need to pass into a function what all of the values are.

My question applies to situations besides just creating plots, though.

Essentially, each argument I'm passing is the same, with the index changing ([1] up to [8]). Is there a more concise way of writing this? This will come in handy when I create a plot that has 30+ dropdown options.

buttons = list(
  unique(df$FAC_DESCRIPTION)[1],
  unique(df$FAC_DESCRIPTION)[2],
  unique(df$FAC_DESCRIPTION)[3],
  unique(df$FAC_DESCRIPTION)[4],
  unique(df$FAC_DESCRIPTION)[5],
  unique(df$FAC_DESCRIPTION)[6],
  unique(df$FAC_DESCRIPTION)[7],
  unique(df$FAC_DESCRIPTION)[8]
)

EDIT: The code I pasted above is actually a simplified version of what I'm actually trying to do, and when I used the [1:8] method it didn't work. This is closer to the actual code (shortened to the first three elements only, not 8:

buttons = list(
            list(method = "r",args = list("t[0].value", unique(df$FAC)[1]),label =unique(df$FAC)[1]), 
            list(method = "r",args = list("t[0].value", unique(df$FAC)[2]),label =unique(df$FAC)[2]), 
            list(method = "r",args = list("t[0].value", unique(df$FAC)[3]),label =unique(df$FAC)[3])
)

However, when I tried the below, it didn't work -- is that because I'm using it in two places?

buttons = list(
            list(method = "r",args = list("t[0].value", unique(df$FAC)[1:3]),label =unique(df$FAC)[1:3])
)

I also tried:

dropdown_options <- lapply(1:5, function(x)list(paste('method = "r", args = list("transforms[0].value", unique(df$FAC)[',x,']),label = unique(df$FAC)[',x,']',sep='')))

buttons = do.call(list, dropdown_options)

But that didn't work either.

Big D
  • 15
  • 5
  • 5
    In general, see `?do.call`. This, however, looks like `buttons = as.list(unique(df$FAC_DESCRIPTION)[1:8])`. The `[1:8]` isn't needed if there are only 8 unique values. – Gregor Thomas Jul 17 '19 at 23:01
  • It's extremely hard to read unformatted code in comments. If the exmaple in your question isn't very good, just edit your question to use the new example instead. – Gregor Thomas Jul 18 '19 at 18:37
  • @Gregor I edited the question, any chance you could take another look? – Big D Jul 18 '19 at 20:39

1 Answers1

0

Your lapply attempt is close, but you need to use a regular function, not paste. unique(df$FAC)[x] isn't a string in your original code, so it shouldn't be a string in your lapply.

dropdown_options <- lapply(1:5, function(x) {
  list(method = "r", 
       args = list(
         "t[0].value",
         unique(df$FAC)[x]),
       label = unique(df$FAC)[x]
      )}
)

That should be equivalent, though unless you share some sample df$FAC data I cannot test.

Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294