I have a routine in R that takes a variable number of arguments, and I need to call this routine passing an unpacked list. In python I would do
lst = [1,2,3]
my_func(*lst)
What is the equivalent syntax in R?
To be more specific, I am using shiny and I am trying to create a dynamic list of entries
This is the code.
server <- function(input, output) {
applist <- c(
a(href="#", class="list-group-item",
h4(class="list-group-item-heading", "Entry 1"),
p(class="list-group-item-text", "Description")
),
a(href="#", class="list-group-item",
h4(class="list-group-item-heading", "Entry 2"),
p(class="list-group-item-text", "Description")
))
output$applist = renderUI(
div(class="list-group", ... applist)
)
}
The asterisk (star) operator is used in Python with more than one meaning attached to it. For numeric data types, * is used as multiplication operator >>> a=10;b=20 >>> a*b 200 >>> a=1.5; b=2.5; >>> a*b 3.75 >>> a=2+3j; b=3+2j >>> a*b 13j.
Here single asterisk( * ) is also used in *args. It is used to pass a variable number of arguments to a function, it is mostly used to pass a non-key argument and variable-length argument list.
The starred expression will create a list object, although we start with a tuple object. Starred expressions can be used with more than just tuples, and we can apply this technique for other iterables (e.g., lists, strings).
Unpacking in Python refers to an operation that consists of assigning an iterable of values to a tuple (or list ) of variables in a single assignment statement. As a complement, the term packing can be used when we collect several values in a single variable using the iterable unpacking operator, * .
Posted by OP.
Here is how I solved. using do.call
does the trick, but you have to be aware that lists in python is not the same as lists in R. A list in R is more similar to a mix of a dictionary and a list.
applist <- list(
class="list-group",
a(href="#", class="list-group-item"),
a(href="#", class="list-group-item")
)
output$applist = renderUI(do.call(div, applist))
Note how the applist contains both a named entry class
and non-named entries. As I said, hybrid. The do.call
then does the "unpacking", but the content of applist is then distributed as named or non-named argument. It works differently from python, where named and non-named are always separated.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With