Hi all,
Is there a way to declare vectors as parameters in R. Example, I have a function(finat_DT(data)
) that returns DTtable. So here data parameter is datasets. But can we pass another arguement like finat_DT(data, column_hidden = a)
so that we can declare ````a````` as below
columnDefs = list(list(visible=FALSE, targets=a))
So when we call finat_DT(data, column_hidden = c(1,2))
#only first 2 columns gets hidden.
similarly finat_DT(data, column_hidden = c(1,2,6))
# only 1, 2 and 6 columns gets hidden
Is this possible to achieve?
Below is the sample example
library(shiny)
library(DT)
ui <- fluidPage(
dataTableOutput("tabout")
)
server <- function(input, output, session) {
small_fun <- function(data,c = a){
return(DT::datatable(data,options = list(columnDefs = list(list(visible=FALSE, targets=a)))))
}
output$tabout <- renderDataTable({
small_fun(iris,c = 3)
})
}
shinyApp(ui, server)
FJCC
March 1, 2021, 1:45pm
2
Inside of small_fun, the index of the columns you want to have hidden is stored in c
, so you need to set targets = c
.
small_fun <- function(data,c = a){
return(DT::datatable(data,options = list(columnDefs = list(list(visible=FALSE, targets=c)))))
}
In fact, a
is not defined anywhere, so setting c=a
as the default for the function does not do anything helpful.
Great. But can we keep parameter c optional. Example if I need not format any columns. Can we do below
function(data) ## so that no format happens
FJCC
March 1, 2021, 3:10pm
4
You can pass NULL to c
if you want all of the columns to be shown.
server <- function(input, output, session) {
small_fun <- function(data,c = NULL){
return(DT::datatable(data,options = list(columnDefs = list(list(visible=FALSE, targets=c)))))
}
output$tabout <- renderDataTable({
small_fun(iris)
})
}
Great thanks, But i just tried differently. When i try below, it wont work (Getting error)
small_fun <- function(data,c = NULL){
return(DT::datatable(data) %>% formatCurrency(columns = c, currency = "", interval = 3, mark = ",",digits = 2))
}
Error : zero-length inputs cannot be mixed with those of non-zero length
FJCC
March 2, 2021, 1:54pm
6
I suggest you use something like
small_fun <- function(data,c = NULL){
if (is.null(c)) {
return(DT::datatable(data)
} else {
return(DT::datatable(data) %>% formatCurrency(columns = c, currency = "", interval = 3, mark = ",",digits = 2))
}
}
system
Closed
April 1, 2021, 6:47am
8
This topic was automatically closed 21 days after the last reply. New replies are no longer allowed. If you have a query related to it or one of the replies, start a new topic and refer back with a link.