R: Assign vector element as list variable name - r

Here is the end result that I would like to achieve:
json_creative_pause = list("47770124" =
list(patch = list(
`$set` = list (
status = "PAUSED"
))))
The issue is that I would like to create this same structure dynamically for multiple ids. I have this variable:
creative_ids_to_pause = c("75196186", "78369656", "80050466")
And I would like to recreate the same structure for each creative id. But running such code doesn't really work:
json_creative_pause = list(get(creative_ids_to_pause[1]) =
list(patch = list(
`$set` = list (
status = "PAUSED"
))))
Does anyone know how to assign a vector element as a variable name inside of a list?
Thank you for your help!
Arben

We can use setNames
setNames(list(patch = list(
`$set` = list (
status = "PAUSED"
))), creative_ids_to_pause[1])
#$`75196186`
#$`75196186`$`$set`
#$`75196186`$`$set`$status
#[1] "PAUSED"
Or another option is dplyr::lst
dplyr::lst(!! creative_ids_to_pause[1] :=
list(patch = list(
`$set` = list (
status = "PAUSED"
))))
#$`75196186`
#$`75196186`$patch
#$`75196186`$patch$`$set`
#$`75196186`$patch$`$set`$status
#[1] "PAUSED"

I also found this solution:
creative_ids_to_pause = c("75196186", "78369656", "80050466")
unnamed_json_structure = list(
patch = list(
`$set` = list(
status = "PAUSED"
)))
list_all_creative_ids = list()
for(i in 1:length(creative_ids_to_pause)){
list_all_creative_ids[[creative_ids_to_pause[i]]] = unnamed_json_structure
}
list_all_creative_ids %>%
toJSON(pretty = TRUE, auto_unbox = TRUE)
Result
"75196186": {
"patch": {
"$set": {
"status": "PAUSED"
}
}
},
"78369656": {
"patch": {
"$set": {
"status": "PAUSED"
}
}
},
"80050466": {
"patch": {
"$set": {
"status": "PAUSED"
}
}
}
}

Related

How to add multiple scrollbar in R Shiny data table

I am trying to build a shiny app that has the following feature:
It has a parent-child feature that can expand and collapse as per
user interaction (Requirement 1 - Done)
When the rows are expanded, several child rows are displayed in the
data table. I want to introduce multiple scroll bars in this table.
1st scrollbar will be for 1st 4 columns and another scrollbar for the
rest of the columns. (Requirement 2 - Not Done)
The below code is able to produce results for the 1st requirement (using JQuery) however, I am unable to find a way out for Requirement 2.
Can anyone assist here?
packages = c(
'shiny',
'shinydashboard',
'tidyverse',
'dplyr',
'magrittr',
'plotly',
'ggplot2',
'scales',
'DT',
"shinyWidgets",
"fontawesome"
)
for (p in packages) {
if (!require(p, character.only = T)) {
install.packages(p)
}
library(p, character.only = T)
}
DataIn <- mtcars
DataIn <- DataIn %>% tidyr::nest(-cyl)
DataIn <- DataIn %>%
{
bind_cols(data_frame(
' ' = rep(
'<img src=\"https://raw.githubusercontent.com/DataTables/DataTables/master/examples/resources/details_open.png\"/>',
nrow(.)
)
), .)
}
# get dynamic info and strings
nested_columns <-
which(sapply(DataIn, class) == "list") %>% setNames(NULL)
not_nested_columns <-
which(!(seq_along(DataIn) %in% c(1, nested_columns)))
not_nested_columns_str <-
not_nested_columns %>% paste(collapse = "] + '_' + d[") %>% paste0("d[", ., "]")
CallBack <- paste0(
"
table.column(1).nodes().to$().css({cursor: 'pointer'});
// Format data object (the nested table) into another table
var format = function(d) {
if(d != null){
var result = ('<table id=\"child_' + ",
not_nested_columns_str,
" + '\">') + '<thead><tr>'
for (var col in d[",
nested_columns,
"][0]){
result += '<th>' + col + '</th>'
}
result += '</tr></thead></table>'
return result
}else{
return '';
}
}
var format_datatable = function(d) {
var dataset = [];
for (i = 0; i <= d[",
nested_columns,
"].length-1; i++) {
var datarow = $.map(d[",
nested_columns,
"][i], function(value, index) {
return [value];
});
dataset.push(datarow);
}
var subtable = $(('table#child_' + ",
not_nested_columns_str,
")).DataTable({
'data': dataset,
'autoWidth': true,
'deferRender': true,
'info': false,
'lengthChange': false,
'ordering': true,
'paging': false,
'scrollX': false,
'scrollY': false,
'searching': false
// 'fnRowCallback': function (nRow, aData, iDisplayIndex, iDisplayIndexFull) {
// $('td', nRow).css('background-color', 'Red')}
});
};
table.on('click', 'td.details-control', function() {
var td = $(this), row = table.row(td.closest('tr'));
if (row.child.isShown()) {
row.child.hide();
td.html('<img src=\"https://raw.githubusercontent.com/DataTables/DataTables/master/examples/resources/details_open.png\"/>');
} else {
row.child(format(row.data())).show();
td.html('<img src=\"https://raw.githubusercontent.com/DataTables/DataTables/master/examples/resources/details_close.png\"/>');
format_datatable(row.data())
}
});"
)
shinyApp(
ui = fluidPage(DT::dataTableOutput('tbl')),
server = function(input, output) {
output$tbl = DT::renderDataTable(datatable(
DataIn,
escape = -2,
# raw HTML in column 2
options = list(columnDefs = list(
list(visible = FALSE, targets = c(0, nested_columns)),
# Hide row numbers and nested columns
list(
orderable = FALSE,
className = 'details-control',
targets = 1
) # turn first column into control column
)),
callback = JS(CallBack)
))
}
)

Problem getting current list of input values in Shiny

I'm having quite a few problems to get the updated values from several coonditionalPanels. I created a reactive variable parList which should contain the parN_sig input variables. These variables should come from conditional panels and they are all named parN_sig. I do not know why but I always end up getting values from the double_sig panel when another panel is shown at the UI.
Here's my code:
ui.r
jscode <- "
shinyjs.disableTab = function(name) {
var tab = $('.nav li a[data-value=' + name + ']');
tab.bind('click.tab', function(e) {
e.preventDefault();
return false;
});
tab.addClass('disabled');
}
shinyjs.enableTab = function(name) {
var tab = $('.nav li a[data-value=' + name + ']');
tab.unbind('click.tab');
tab.removeClass('disabled');
}
"
css <- "
.nav li a.disabled {
background-color: #aaa !important;
color: #333 !important;
cursor: not-allowed !important;
border-color: #aaa !important;
}"
# Create Shiny object
library(shiny)
library(shinythemes)
library(shinyjs)
library(ggplot2)
library(grid)
library(egg)
# source("input.r")
source("functions.r")
formula_tabs<-tabsetPanel(
tabPanel("double_sig",
withMathJax("$$y=d+\\frac{a}{1+exp^{-b*(t-c)}}+\\frac{e}{1+exp^{-f*(t-g)}}$$")
),
tabPanel("gompertz",
withMathJax("$$y=b*exp^{\\ln(\\frac{c}{b})*exp^{-a*t}}$$")
),
tabPanel("verhulst",
withMathJax("$$y=\\frac{b*c}{b+(b-c)*exp^{-a*t}}$$")
),
id = "formulas",
type = "tabs"
)
fluidPage(useShinyjs(),theme = shinytheme("lumen"),useShinyjs(),tags$style("#params { display:none; } #formulas { display:none; }"),
extendShinyjs(text = jscode),inlineCSS(css),
navbarPage("Protein turnover model",id="tabs",
tabsetPanel(tabPanel("Input data",
checkboxInput("multiple","Single file",value = FALSE),
uiOutput("mult_files"),
uiOutput("sing_file"),
actionButton("disp_distr","Show distributions"),
plotOutput("distr_plot"),
plotOutput("distr_stade")
),
tabPanel("Weight fitting",
fileInput("weight_data","Choose weight data to be fitted",accept = c("text/csv")),
div(style="display:inline-block",selectInput("method_we","Select fitting formula",choices = c("Logistic"="verhulst","Gompertz"="gompertz","Empiric"="empirique","Log polynomial"="log_poly","Double sigmoid"="double_sig"))),
div(style="display:inline-block",formula_tabs), ## "Contois"="contois",,"Noyau"="seed",
conditionalPanel("input.method_we=='verhulst'",textInput("par1_sig","Enter value of a",value =0.1),
textInput("par2_sig","Enter value of b",value = 100),
textInput("par3_sig","Enter value of c",value = 1)),
conditionalPanel("input.method_we=='gompertz'",textInput("par1_sig","Enter value of a",value =0.065),
textInput("par2_sig","Enter value of b",value = 114.39),
textInput("par3_sig","Enter value of c",value = 0.52)),
conditionalPanel("input.method_we=='empirique'",textInput("par1_sig","Enter value of a",value =5.38),
textInput("par2_sig","Enter value of b",value = 8),
textInput("par3_sig","Enter value of c",value = 7)),
conditionalPanel("input.method_we=='double_sig'",textInput("par1_sig","Enter value of a",value = 48),
textInput("par2_sig","Enter value of b",value = 0.144),
textInput("par3_sig","Enter value of c",value = 35),
textInput("par4_sig","Enter value of d",value = 0.4),
textInput("par5_sig","Enter value of e",value = 48),
textInput("par6_sig","Enter value of f",value = 0.042),
textInput("par7_sig","Enter value of g",value = 90)),
actionButton("fit_op","Fit"),
plotOutput("fitplot")
),
tabPanel("mRNA fitting and calculation",
textInput("ksmin","Value of ksmin",value =3*4*3*3.6*24),
selectInput("fit_mrna","Select fitting formula",choices=c("3rd degree polynomial"="3_deg","6th degree polynomial"="6_deg","3rd degree logarithmic polynomial"="3_deg_log")),
actionButton("run_loop","Run calculation"),
disabled(downloadButton("downFile","Save results"))
),
tabPanel("Results",id="tabRes",
uiOutput("select_res"),
plotOutput("fit_prot_plot")
)
))
)
server.r
library(shiny)
library(shinythemes)
library(shinyjs)
library(ggplot2)
library(grid)
library(egg)
# source("input.r")
source("functions.r")
function(input, output, session) {
js$disableTab("tabRes")
fit_op<-reactiveValues(data=NULL)
run_calc<-reactiveValues(data=NULL)
en_but<-reactiveValues(enable=FALSE)
theme<<-theme(panel.background = element_blank(),panel.border=element_rect(fill=NA),panel.grid.major = element_blank(),panel.grid.minor = element_blank(),strip.background=element_blank(),axis.text.x=element_text(colour="black"),axis.text.y=element_text(colour="black"),axis.ticks=element_line(colour="black"),plot.margin=unit(c(1,1,1,1),"line"))
output$mult_files<-renderUI({
if (!input$multiple){
tagList(fileInput("prot_file","Choose protein file"),
fileInput("mrna_file","Choose transcript file"))
}
})
output$sing_file<-renderUI({
if (input$multiple){
tagList(textInput("protein_tab","Name of protein tab",value = "Proteines"),
textInput("rna_tab","Name of mRNA tab",value = "Transcrits"),
fileInput("data_file","Choose xls/xlsx file",accept=c(".xls",".xlsx")))
}
})
observeEvent(input$method_we, {
# updateTabsetPanel(session, "params", selected = input$method_we)
updateTabsetPanel(session,"formulas",selected = input$method_we)
})
observe({
if(!is.null(input$data_file)){
inFile<-input$data_file
list_data<-loadData(inFile$datapath,input$rna_tab,input$protein_tab,poids=F)
mrna_data<-list_data$mrna
prot_data<-list_data$prot
test_list<-list_data$parse
test_list<<-sample(test_list,3)
clean_mrna_data<<-mrna_data[,-which(is.na(as.numeric(as.character(colnames(mrna_data)))))]
clean_prot_data<<-prot_data[,-which(is.na(as.numeric(as.character(colnames(prot_data)))))]
}
})
observe({
if((!is.null(input$prot_file)) & (!is.null(input$mrna_file))){
protFile<-input$prot_file
mrnaFile<-input$mrna_file
prot_data<-loadData(protFile$datapath,"","",poids=F)
mrna_data<-loadData(mrnaFile$datapath,"","",poids=F)
clean_mrna_data<<-mrna_data[,-which(is.na(as.numeric(as.character(colnames(mrna_data)))))]
clean_prot_data<<-prot_data[,-which(is.na(as.numeric(as.character(colnames(prot_data)))))]
total_data<-merge(mrna_data,prot_data)
lista<-vector("list",nrow(mrna_data))
for (i in seq(1,nrow(total_data))){
lista[[i]]<-list("Protein_ID"=total_data[i,"Protein"],"Transcrit_ID"=total_data[i,"Transcrit"],"Transcrit_val"=as.matrix(total_data[i,3:29]),"Protein_val"=as.matrix(total_data[i,30:ncol(total_data)]),"DPA"=t)
}
# test_list<<-lista
test_list<<-sample(lista,3)
}
})
observeEvent(input$disp_distr,{
print("Plotting...")
output$distr_plot<-renderPlot({print(combineGraphs(clean_mrna_data,clean_prot_data,"",moyenne = T))})
print("Finished")
})
# parList<-reactiveValues()
# observe({
# for (i in reactiveValuesToList(input)){
# print(i)
# if (grepl("par[1-9]+_sig",i,perl = T)){
# newlist[[input[[i]]]]<-input[[i]]
# }
# }
# # })
parList<-reactive({
x<-reactiveValuesToList(input)
x_ind<-grep("par[1-9]+",names(x),perl = T)
newlist<-vector("list",length(x_ind))
names(newlist)<-names(x[x_ind])
for (el in names(newlist)){
newlist[[el]]<-as.numeric(as.character(input[[el]]))
}
names(newlist)<-gsub("_sig","",names(newlist))
newlist<-newlist[order(names(newlist))]
newlist
})
observeEvent(input$fit_op,{
browser()
print(parList())
inFile<-input$weight_data
days_kiwi<-rep(c(0,13,26,39,55,76,118,179,222), each = 3)
poids_data<-loadData(inFile$datapath,"","",poids=T)
print("Fitting...")
tryCatch({
coefs_poids<<-fitPoids_v2(poids_data[,1],poids_data[,2],input$method_we,parList())
},
warning = function(warn){
showNotification(paste0(warn), type = 'warning')
},
error = function(err){
showNotification(paste0(err), type = 'err')
})
print(coefs_poids$coefs)
val_mu<-mu(c(poids_data$DPA),input$method_we,coefs_poids$coefs,coefs_poids$formula,dpa_analyse = NULL)
data_mu<-data.frame("DPA"=c(poids_data$DPA),"Mu"=val_mu)
g_mu<<-ggplot(data_mu,aes(x=DPA,y=Mu))+geom_line()+theme+xlab("DPA")+ylab("Growth rate (days^-1)")
fit_op$state<-TRUE
print("Finished!!")
output$fitplot<-renderPlot({
req((fit_op$state)==TRUE,exists("coefs_poids"))
ggarrange(coefs_poids$graph,g_mu,ncol=2)
})
})
observeEvent(input$run_loop,{
if (input$fit_mrna!=""){
ksmin=as.numeric(as.character(input$ksmin))
score=0
cont<-0
poids_coef<<-coefs_poids$coefs
formula_poids<<-coefs_poids$formula
mess<-showNotification(paste("Running..."),duration = NULL,type = "message")
for (el in test_list){
tryCatch({
run_calc$run<-TRUE
cont<-cont+1
print(cont)
norm_data<-normaMean(el$Protein_val,el$Transcrit_val,ksmin)
fittedmrna<<-fit_testRNA(el$DPA,norm_data$mrna,"3_deg")
par_k<-solgss_Borne(el$DPA,as.vector(norm_data$prot),as.numeric(norm_data$ks),score)
par_k[["plot_fit_prot"]]<-plotFitProt(el$DPA,as.vector(norm_data$prot),par_k$prot_fit)
X<-matrice_sens(el$DPA,par_k[["solK"]][,1])
diff<-(par_k[["error"]][["errg"]][1]*norm(as.vector(norm_data$prot),"2"))^2
par_k[["corr_matrix"]]<-matrice_corr(X,length(norm_data$prot),diff)
if (!is.null(par_k)){
test_list[[cont]]$SOL<-par_k
# write.csv(test_list[[cont]][["SOL"]][["solK"]],paste("solK/",paste(test_list[[cont]][["Transcrit_ID"]],"_Sol_ks_kd.csv"),sep = ""))
}
},error=function(e){showNotification(paste0("Protein fitting not achieved for ",el$Transcrit_ID,sep=" "),type = "error",duration = NULL)})
}
valid_res<<-Filter(function(x) {length(x) > 5}, test_list)
print(valid_res[[1]])
mess<-showNotification(paste("Finished!!"),duration = NULL,type = "message")
en_but$enable<-TRUE
}
})
output$downFile<-downloadHandler(
filename = function(){
paste("results_KsKd-",Sys.Date(),".zip",sep="")
},
content = function(file){
owd <- setwd(tempdir())
on.exit(setwd(owd))
files <- NULL;
for (res in valid_res){
fileName<-paste(res[["Transcrit_ID"]],"_Sol_ks_kd.csv",sep = "")
write.csv(res[["SOL"]][["solK"]],fileName)
files<-c(files,fileName)
}
zip(zipfile = file,files = files)
if(file.exists(paste0(file, ".zip"))) {file.rename(paste0(file, ".zip"), file)}
},contentType = "application/zip"
)
observe({
if (en_but$enable){
enable("downFile")
}
})
}
I recently started using Shiny, so any help would be extremely appreciated. Thanks in advance!
Welcome to SO.
You've identified the problem yourself: "...are all named parN_sig". That means you don't have several inputs, you only have one. So you always get the value of (say) input$par2_sig from the first conditional panel regardless of which panel you're trying to access.
You have two options:
Provide unique names for every textInput. That will be a pain. Or...
Use modules. They take a bit of getting used to, but are worth the effrt in the end.
If you set the module up correctly, you'll be able to use the same module for each conditional panel, even though they have different numbers of textinputs.
See this page for help on creating your first module.

R Shiny Datatable Child Row Selection and Info Issue

I am having an issue selecting the child rows in a R Shiny DT Table with JS callback.
When expanding the parent row, I try to select the child rows, and all rows are selected in that child (including child's background).
If I select 2nd child row, the background is deselcted and it shows my 2 childs selected (every other click selects all child rows, then shows ones selected repeatedly)
Also, how to get the information on which child rows are selected?
Thank you very much!
Alex B
I am trying to play with the datatable settings in the JS callback.
'''
library(data.table)
library(DT)
library(shiny)
library(jsonlite)
ui <- fluidPage(DT::dataTableOutput(width = "100%", "table"))
server <- function(input, output) {
output$table = DT::renderDataTable({
mtcars_dt = data.table(mtcars)
setkey(mtcars_dt,mpg,cyl)
mpg_dt = unique(mtcars_dt[, list(mpg, cyl)])
setkey(mpg_dt, mpg, cyl)
cyl_dt = unique(mtcars_dt[, list(cyl)])
setkey(cyl_dt, cyl)
mtcars_dt = mtcars_dt[, toJSON(.SD), by = list(mpg,cyl)]
setnames(mtcars_dt,'V1','mtcars')
mtcars_dt[, ' ' := '►']
df1 = mtcars_dt
df1 = df1[c(1,6),]
setcolorder(df1, c(length(df1),c(1:(length(df1) - 1))))
DT::datatable(
data = df1,
rownames = FALSE,
escape = FALSE,
selection="multiple",
options = list(
# dom = 'Bfrti',
stripeClasses = list(),
deferRender = TRUE,
# scrollX = TRUE,
pageLength = 25,
scrollY = "1000",
scroller = TRUE,
scollCollapse = TRUE,
lengthMenu = c(20, 50, 100, 500),
searchHighlight = TRUE,
tabIndex = 1,
columnDefs = list(
list(orderable = FALSE, className = 'details-control', targets = 0),
list(visible = FALSE, targets = -1 )
)
),
callback = JS("
//table.header().to$().css({'background-color': '#000', 'color': '#fff'})
table.column(01).nodes().to$().css({cursor: 'pointer'})
var table_id = 1000
// Format child object into another table
var format = function(table_id, columns) {
if(columns != null){
var result = ('<table id=\"' + table_id + '\"><thead><tr>')
for (var i in columns){
result += '<th>' + columns[i] + '</th>'
}
result += '</tr></thead></table>'
return result
}else{
return ''
}
}
var format_datatable = function( table_id, newtable, columns) {
if(newtable != null){
var column_defs = []
for (var i in columns)
{
if (i == 0)
{
column_defs[i] = {'data': columns[i], 'targets': parseInt(i), 'orderable': false, 'className': 'details-control'}
}
else
{
column_defs[i] = {'data': columns[i], 'targets': parseInt(i)}
}
}
/* alert(JSON.stringify(column_defs)) */
//var printTable = document.getElementById(newtable)
//document.write(newtable)
//document.write(columns)
var subtable = $(('table#' + table_id)).DataTable({
'data': newtable,
'autoWidth': false,
'deferRender': true,
'stripeClasses': [],
'info': false,
'select': { style: 'os',
},
'lengthChange': false,
'ordering': false,
'paging': false,
'scrollX': false,
'scrollY': false,
'searching': false,
'columnDefs': column_defs
}).draw()
}
}
table.on('click', 'td.details-control', function() {
var td = $(this)
var table = $(td).closest('table')
var row = $(table).DataTable().row(td.closest('tr'))
if (row.child.isShown()) {
row.child.hide()
td.html('►')
}
else
{
var row_data = row.data()
if (!Array.isArray(row_data))
{
row_data = Object.keys(row_data).map(function (key) {
return row_data[key]
});
}
var newtable = JSON.parse(row_data[row_data.length-1])
var columns = Object.keys(newtable[0])
table_id++
row.child(format(table_id, columns)).show()
format_datatable(table_id, newtable, columns)
console.log(table_id)
td.html('▼')
}
})
")
)
})
observe({
print(input$table_rows_selected)
print(input$newtable_rows_selected)
})
}
shinyApp(ui = ui, server = server)
'''
I would like to highlight individual child rows and know which child rows are selected. Currently it highlights all child rows each time it clicks.
Here is an attempt. This works, but the selection on the main table is disabled.
library(data.table)
library(DT)
library(shiny)
library(jsonlite)
initComplete <- paste(
"function(settings){",
" var table = settings.oInstance.api();",
" var tbl = table.table().node();",
" var id = $(tbl).closest('.dataTable').attr('id');",
" table.on('click', 'tbody tr', function(){",
" // send selected columns to Shiny",
" setTimeout(function(){",
" var indexes = table.rows({selected:true}).indexes();",
" var indices = Array(indexes.length);",
" for(var i = 0; i < indices.length; ++i){",
" indices[i] = indexes[i];",
" }",
" Shiny.setInputValue('childrow_rows_selected', {child: id, rows: indices});",
" },0);",
" });",
"}",
sep = "\n"
)
ui <- fluidPage(DT::dataTableOutput(width = "100%", "table"))
server <- function(input, output) {
output$table = DT::renderDataTable({
mtcars_dt = data.table(mtcars)
setkey(mtcars_dt,mpg,cyl)
mpg_dt = unique(mtcars_dt[, list(mpg, cyl)])
setkey(mpg_dt, mpg, cyl)
cyl_dt = unique(mtcars_dt[, list(cyl)])
setkey(cyl_dt, cyl)
mtcars_dt = mtcars_dt[, toJSON(.SD), by = list(mpg,cyl)]
setnames(mtcars_dt,'V1','mtcars')
mtcars_dt[, ' ' := '►']
df1 = mtcars_dt
df1 = df1[c(1,6),]
setcolorder(df1, c(length(df1),c(1:(length(df1) - 1))))
DT::datatable(
data = df1,
rownames = FALSE,
escape = FALSE,
selection = "none",
extensions = "Select",
options = list(
# dom = 'Bfrti',
stripeClasses = list(),
deferRender = TRUE,
# scrollX = TRUE,
pageLength = 25,
scrollY = "1000",
scroller = TRUE,
scollCollapse = TRUE,
lengthMenu = c(20, 50, 100, 500),
searchHighlight = TRUE,
tabIndex = 1,
columnDefs = list(
list(orderable = FALSE, className = 'details-control', targets = 0),
list(visible = FALSE, targets = -1 )
)
),
callback = JS("
table.column(0).nodes().to$().css({cursor: 'pointer'});
// var table_id = 1000
// Format child object into another table
var format = function(table_id, columns) {
if(columns != null){
var result = ('<table id=\"' + table_id + '\"><thead><tr>')
for (var i in columns){
result += '<th>' + columns[i] + '</th>'
}
result += '</tr></thead></table>'
return result
}else{
return ''
}
}
var format_datatable = function( table_id, newtable, columns) {
if(newtable != null){
var column_defs = []
for (var i in columns)
{
if (i == 0)
{
column_defs[i] = {'data': columns[i], 'targets': parseInt(i), 'orderable': false, 'className': 'details-control'}
}
else
{
column_defs[i] = {'data': columns[i], 'targets': parseInt(i)}
}
}
var subtable = $(('table#' + table_id)).DataTable({
'data': newtable,",
sprintf("initComplete: %s,", initComplete),
" 'autoWidth': false,
'deferRender': true,
'stripeClasses': [],
'info': false,
'select': {style: 'multi'},
'lengthChange': false,
'ordering': false,
'paging': false,
'scrollX': false,
'scrollY': false,
'searching': false,
'columnDefs': column_defs
}).draw()
}
}
table.on('click', 'td.details-control', function() {
var td = $(this);
var table = $(td).closest('table');
var row = $(table).DataTable().row(td.closest('tr'));
var table_id = 'child' + row.index();
if (row.child.isShown()) {
row.child.hide();
td.html('►');
}
else
{
var row_data = row.data();
if (!Array.isArray(row_data))
{
row_data = Object.keys(row_data).map(function (key) {
return row_data[key];
});
}
var newtable = JSON.parse(row_data[row_data.length-1])
var columns = Object.keys(newtable[0])
//table_id++
row.child(format(table_id, columns)).show()
format_datatable(table_id, newtable, columns)
console.log(table_id)
td.html('▼')
}
})
")
)
})
observe({
# print(input$table_rows_selected)
# print(input$newtable_rows_selected)
print(input$childrow_rows_selected)
})
}
shinyApp(ui = ui, server = server)

Highcharts - drill down to multiple series in R

I know this has already been answered in JS but I was hoping for a solution using highcharter in R. Highcharts - drill down to multiple series
I'm new to JS and also not that familiar with the highcharter library in R so any help would be greatly appreciated. The following code compiles but as the code is more experimental than anything it does not allow me to drill down to a multi- series chart as hoped.
DATABrowser = list(list(y= 55.11
,drilldown = list(
name = 'MSIE versions',
categories = list('MSIE 6.0', 'MSIE 7.0', 'MSIE 8.0',
'MSIE 9.0'),
series = list(list(
type = 'spline',
name = 'MSIE versions 2000',
data = list(10.85, 7.35, 33.06, 2.81)
),list(
type = 'spline',
name = 'MSIE versions 2010',
data = list (1, 5, 10, 15)
))
)),list(y = 21.6),list(y = 11.6),list(y = 7.3),list(y =
2.6)
)
categories = list('MSIE', 'Firefox', 'Chrome', 'Safari', 'Opera')
name = 'Browser brands'
fn <-"function () {
var drilldown = this.drilldown;
var len = chart.series.length;
var name = null, catergories = drilldown.categories, data = drilldown, type
=drilldown.type;
chart.xAxis[0].setCategories(categories);
for(var i = 0; i < len; i++){
chart.series[0].remove();
}
if(data.series){
for( i = 0; i < data.series.length; i ++ ){
chart.addSeries({
name: data.series[i].name,
data: data.series[i].data,
type: data.series[i].type,
});
}
} else {
chart.addSeries({
name: name,
data: data,
type: type,
});
}
}
"
hc = highchart() %>%
hc_chart(type = "column") %>%
hc_title(text = "Basic Drilldown Big Bossing") %>%
hc_xAxis(categories = categories) %>%
hc_add_series(
name = name
,data = DATABrowser
) %>% hc_plotOptions(
column = list(
# allowPointSelect = TRUE,
cursor = "pointer",
point = list(
events = list(
click = JS(fn)
)
)
)
)
hc
The JS function returns an error
chart is undefined
Indeed we don't have access to the chart from the click event, but we can retrive it with:
var chart = Highcharts.charts[0]
So putting that inside the JS, together with some typo fix gives us:
fn <-"function () {
var chart = Highcharts.charts[0];
var drilldown = this.drilldown;
var len = chart.series.length;
var name = null,
categories = drilldown.categories,
data = drilldown,
type = drilldown.type;
chart.xAxis[0].setCategories(categories);
for(var i = 0; i < len; i++){
chart.series[0].remove();
}
if(data.series){
for( i = 0; i < data.series.length; i ++ ){
chart.addSeries({
name: data.series[i].name,
data: data.series[i].data,
type: data.series[i].type,
});
}
} else {
chart.addSeries({
name: name,
data: data,
type: type,
});
}
}
"
Giving us:
library(highcharter)
highchart() %>%
hc_chart(type = "column") %>%
hc_title(text = "Basic Drilldown Big Bossing") %>%
hc_xAxis(categories = categories) %>%
hc_add_series(
name = name
,data = DATABrowser
) %>% hc_plotOptions(
column = list(
# allowPointSelect = TRUE,
cursor = "pointer",
point = list(
events = list(
click = JS(fn)
)
)
)
)

Oracle R Enterprise: Error ORE object has no unique key

I need to make a function which call Oracle R Enterprise ore.corr function and output result as a data.frame.
My R code here:
f_sts_corelation =
function(dat, target_col="",corr_type="spearman",group_by="")
{
v_target_col = gsub("\n","",target_col, fixed = TRUE);
v_target_col_list = "";
library("gdata");
for (s_name in strsplit(v_target_col,",")[[1]])
{
n_pos = regexpr(".",s_name,fixed = TRUE);
if (n_pos > 0)
{
s_name = substring(s_name,n_pos+1);
}
s_name = gsub("\"","",s_name, fixed = TRUE);
if (is.numeric(dat[,trim(s_name)]))
{
if (nchar(v_target_col_list)== 0)
{
v_target_col_list = trim(s_name)
}
else
{
v_target_col_list =paste(v_target_col_list,",",trim(s_name))
}
}
}
ore.data = ore.push(dat)
v_id = c()
v_group=c()
v_row = c()
v_col = c()
v_statistic = c()
v_pvalue = c()
v_df = c()
#group_by = ""
s_group_by = trim(gsub("\n","",group_by, fixed = TRUE));
if (nchar(s_group_by) > 0)
{
n_pos = regexpr(".",s_group_by,fixed = TRUE);
if (n_pos > 0)
{
s_group_by = substring(s_group_by,n_pos+1);
}
s_group_by = trim(gsub("\"","",s_group_by, fixed = TRUE));
ore.corr.res = ore.corr(ore.data,var = v_target_col_list, group.by = s_group_by)
for (i in 1:length(ore.corr.res))
{
if (i == 1)
{
v_group = rep(names(ore.corr.res[i]),length(ore.corr.res[[i]]$ROW))
v_row = as.vector(ore.corr.res[[i]]$ROW)
v_col = as.vector(ore.corr.res[[i]]$COL)
v_statistic = as.vector(ore.corr.res[[i]][,3])
v_pvalue = as.vector(ore.corr.res[[i]][,4])
v_df = as.vector(ore.corr.res[[i]][,5])
}
else
{
v_group = c(v_group,rep(names(ore.corr.res[i]),length(ore.corr.res[[i]]$ROW)))
v_row = c(v_row,as.vector(ore.corr.res[[i]]$ROW))
v_col = c(v_col,as.vector(ore.corr.res[[i]]$COL))
v_statistic = c(v_statistic,as.vector(ore.corr.res[[i]][,3]))
v_pvalue = c(v_pvalue,as.vector(ore.corr.res[[i]][,4]))
v_df = c(v_df,as.vector(ore.corr.res[[i]][,5]))
}
}
}
else if(nchar(s_group_by) == 0)
{
ore.corr.res = ore.corr(ore.data,var = v_target_col_list)
v_group = rep(" ",length(ore.corr.res$ROW))
v_row = as.vector(ore.corr.res$ROW)
v_col = as.vector(ore.corr.res$COL)
v_statistic = as.vector(ore.corr.res[,3])
v_pvalue = as.vector(ore.corr.res[,4])
v_df = as.vector(ore.corr.res[,5])
}
df_res = data.frame(Group_by = v_group,
Row = v_row,
Col = v_col,
Statistic = v_statistic,
P_Value = v_pvalue,
DF = v_df)
}
After that, I run the function by following script:
dat = iris;
corr_type="spearman";
V_target_col= '"IRIS_N$10002"."Sepal.Length",
"IRIS_N$10002"."Sepal.Width",
"IRIS_N$10002"."Petal.Width",
"IRIS_N$10002"."Petal.Length"';
group_by =
'
"IRIS_N$10002"."Species"
'
df_result = f_sts_corelation(dat,target_col = target_col, group_by = group_by)
But following error happen.
Error: ORE object has no unique key
I have tried to run each R command inside my function step by step and I sure that the Error happen from the last R command:
df_res = data.frame(Group_by = v_group,
Row = v_row,
Col = v_col,
Statistic = v_statistic,
P_Value = v_pvalue,
DF = v_df)
I don't know how to avoid this error.

Resources