I am working on an app in shiny app o rstudio and I have a question in the second Tab of my app
You see the second tab of my app loads a data.frama written in the app.R file and prints it on rhandsome table, this tab has a selectinput that allows me to change between data.frames which is some I was able todo thanks to reactivevalues functions and correspondingly it does the same thing with the plots (which I make with plotly) the problem is that I am trying to make the values change according to the selected data.frame and the selected
I have tried to do it by using the reactive function, like this
X.var<-reactive({
output$varx <- renderUI({
selectInput("variablex", "Seleccione la variable X", choices=names(TablaD()))
})
})
and
Y.var<-reactive({
output$vary <- renderUI({
selectInput("variabley", "Seleccione la variable y", choices=names(TablaD()))
})
})
but when I use plotly like this
output$plot_three <-renderPlotly({
plot_ly(data=I.Plot(), x = ~X.var(), y = ~Y.var(), name = 'High 2014', type = 'scatter', mode = 'lines',
#x = ~Produccion_de_Energia_Neta, y = ~Produccion_de_Energia_Neta
line = list(color = 'rgb(205, 12, 24)', width = 4)) %>%
layout(title = "Grafico Lineal",
xaxis = list(title = "Valores"),
yaxis = list (title = "Kwh"))
})
and run the app I get the following error
Warning: Error in [: object of type 'closure' is not subsettable
104: recurse
103: FUN
102: lapply
101: traceify
100: plotly_build.plotly
96: getFromNamespace("prepareWidget", "plotly")
95: func
82: origRenderFunc
81: output$plot_three
1: runApp
how should I introduce the variables x = ~X.var()
and y = ~Y.var()
so plotly can accept them and make the plot
Here is the code, like I said before is really long because my app has three tabs my question was in the second tab. Once again thanks for the help and I apologize for the inconveniences. Have a good day
library(shiny)
library(DT)
library(shinydashboard)
library(rhandsontable)
library(devtools)
library(ggplot2)
library(excelR)
library(plotly)
library(shinyjs)
###### Bases de datos para Tab 2
y<-c("TOTAL","Alberto Lovera","Juan Antonio Rodriguez (Pena Larga)","Masparro","Antonio Jose de Sucre (Macagua)","Francisco de Miranda (Caruachi)",
"Simon Bolivar (Guri)","Turboven","Guanapa","Leonardo Ruiz Pineda (San Agaton)","Micro Centrales Hidroelectricas","Cuao","Arautameru","Canaima",
"Kamarata", "Kavanayen","Wonken")
z<-replicate(17, 0)
z1<-c(1,5,6,9,8,2,3,4,7,5,2,1,4,6,9,3,7)
z2<-c(4,4,2,3,5,8,9,5,9,5,6,5,3,6,5,4,8)
z3<-z1+z2
#style = list(A1='background-color:orange; color:green;',
# B1='background-color:orange; color:green;')
Lista=data.frame("Plantas"=y ,"Produccion_de_Energia_Electrica_Bruta"=z1,"Consumo_Interno_y_perdidas_en_Generacion"=z2,"Produccion_de_Energia_Neta"=z3)
##################
a=c(1,2,3,4)
b=c(5,6,7,8)
c=c(sum(a),9,10,11)
#Lista=data.frame(a=a,"Numero_de_Unidades"=b,c=c)
##################
#Capacidad instalada de generacion de energia electrica mensual por tipo de unidad del SEN. a;o 2015
T3<-c(replicate(2," "),"Total sistema Electrico Nacional (SEN)","Total Sistema Interconectado Nacional (SIN)","Hidraulica","Termica",
"Turbo Gas","Turbo Vapor","Ciclo Combinado","Distribuida","Eolico","Plantas Aisladas","Micro Centrales Hidroeletricas","Termica Aislada","Sistema Fotovoltaicos","Sistema para Agua Potable","Sistemas Hibridos")
T3.1<-c("ENE"," ") ;T3.2<-c("FEB"," ") ;T3.3<-c("MAR"," ");T3.4<-c("ABR"," ");T3.5<-c("MAY"," ")
T3.6<-c("JUN"," ");T3.7<-c("JUL"," ");T3.8<-c("AGO"," ");T3.9<-c("SEP"," ");T3.10<-c("OCT"," ");T3.11<-c("NOV"," ")
T3.12<-c("DIC"," "); T3.13<-replicate(15,0)
Tabla3<-data.frame(" "=T3," "=c(T3.2,T3.13)," "=c(T3.3,T3.13)," "=c(T3.4,T3.13)," "=c(T3.5,T3.13)," "=c(T3.6,T3.13)," "=c(T3.7,T3.13)," "=c(T3.8,T3.13)," "=c(T3.9,T3.13)," "=c(T3.10,T3.13)," "=c(T3.11,T3.13)," "=c(T3.1,T3.13),"CAPACIDAD INSTALADA AL CIERRE DEL A;O"=c(T3.12,T3.13) )
#Caracteristicas de las plantas termicas de energia electrica segub tipo de unidad. A;o
T4<-c(" ","Turbo Gas","Alberto Lovera","Alberto Salazar (Anaco)","Guanta","Planta San Diego de Cabrutica",
"Termoelectrica Felix Garcia Casimiro (San Fernando)","La Cabrera","Turboven","Guanapa","Termobarrancas II","Fuente Cayurima","Planta A SIDOR","Pedro Camejo",
"Planta Castillito", "Planta del Este","Termocarabobo","Dabajuro"," Genevapca","Josefa Camejo ","Planta Coro ","Punto fijo ","Planta Ezequequiel Zamora","Argimiro Gabaldon","Enelbar","Planta El Vigia","India Urquia (El Sitio)","Guarenas","Jose Maria Espa;a","La Mariposa","La Raisa ","El Furrial","Jusepin","Petromonagas",
"Petrosinovensa","Santa Barbara (PDVSA)","Luis Caceres de Arismendi","Termoelectrica Antonio Jose de Sucre","Planta Tachira","Monay","Barcazas Josefa Rufina y Margarita","Picure","Antonio Nicolas brice;o","Bajo Grande","Casigua","Guaicaipuro","Rafael Urdaneta","San Lorenzo","San timoteo (PDVSA)","Santa Barbara del Zulia")
T4.1<-c("TOTAL"," ",replicate(3,"Anzoategui"),"Apure",replicate(2,"Aragua"),replicate(2,"Barinas"),replicate(2,"Bolivar"),replicate(4,"Carabobo"),replicate(5,"Falcon"),"Guarico",replicate(2,"Lara"),"Merida",replicate(5,"Miranda"),replicate(5,"Aragua"),replicate(2,"Nueva Esparta"),"Sucre","Tachira","Trujillo",replicate(2,"Vargas"),replicate(8,"Zulia") )
Tabla4<-data.frame("Plantas"=T4,"Entidad Federal"=T4.1,"Numero_de_Unidades"=replicate(50,0),"Capacidad Instalada de Generacion de Energia Electrica (MW)"=replicate(50,0) )
#Caracteristicas de las plantas termicas de energia electrica segub tipo de unidad. A;o (Tabla 2)
T5<-c("Turbo Vapor ","Complejo Agroindustrial Ezequiel Zamora","Planta Centro","Josefa Joaquina Sanchez","Ramon Laguna","Ciclo combinado",
"Planta Don Luis Zambrano","Termozulia","Distribuida","Puerto Ayacucho","Aragua de Barcelona,Bare 10,Bovalle,Cantaura, Clarines,El Cuartel,El Rincon,Santa Ana, Pariaguan","Elorza, Guasdalito, La Macanilla, La Y de Cunaviche, Mantecal","Camatagua, Conisa,Palo Negro, San Jacinto","Arismendi, Barranceas de Barinas, Cuidad Bolivia, Libertad, Puerto Nutrias, Sacapo, Varyna ",
"Caicara del Orinoco, Fuenta Cuayarima, Pijiguaos, Tumeremo", "Guacara","El Baul, Lagunitas","Coro III, Dajarubo, Tucacas","Camaguan","Cano Zancudo, El vigia, Gorsino, Corillo, Yuben, Ortega, Bailadores ","Cantarrana ","Aragua de Maturin, Caicara de Maturin, Caripe, Caripito, Cruz Peraza, Temblador ","Acarigua, Boca de Rio, Canadroma, Los Hernandez, Los Millares, Luisa Caceres, Maparro, Venetur",
"Proarepa","Carupano, Cumanacoa, Guiria, Tres Picos, Yaguaraparo","Caloncito, El Pinol, La Fria, La Tendida, Urena","La Concepcion, Monay","Cojora, Cuatro Esquinas, San Carlos, Quisira","Termicas Aisladas","Atabapo","Manapiabe ","Maroa","Puerto Ayacucho","Rio Negro",
"Guadarrama","Coche","Los Roques")
T5.1<-c(" ","Barinas ","Carabobo","Vargas","Zulia "," ","Merida","Zulia"," ","Amazonas", "Anzoategui","Apure","Aragua","Barinas","Bolivar","Carabobo","Cojedes"," Falcon"," Guarico","Merida","Miranda","Monagas","Nueva Esparta","Portuguesa","Sucre","Tachira","Trujillo","Zulia"," ",replicate(5,"Amazonas"),"Barinas",replicate(2,"Nueva Esparta"))
Tabla5<-data.frame("Plantas"=T5,"Entidad Federal"=T5.1,"Numero de Unidades"=replicate(37,0),"Capacidad Instalada de Generacion de Energia Electrica (MW)"=replicate(37,0) )
#Caracteristicas de las Plantas hidraulicas de Generacion de energia Electrica,A;o
T6<-c(" ","Hidraulicas","Jose Antonio Rodriguez (Pena Larga)","Masparro","Antonio Jose se Sucre (Macagua)","Francisco de Miranda (Caruachi)","Simon Bolivar (Guri)","Fabricio Ojeda (La Vueltosa)","Jose Antonio Paez (Planta Paez)",
"Leonardo Ruiz Pineda (San Agaton)"," Micro Centrales Hidroelectricas","Cuao","Arautameru","Canaima","Kamatara","Kavanayen","Wonken")
T6.1<-c("TOTAL"," ",replicate(2,"Barinas"),replicate(3,"Bolivar"),replicate(2,"Merida"),"Tachira"," ","Amazonas (Rio Cuao)","Bolivar (Salto Arauta)","Bolivar (Salto Hacha)","Bolivar (Quebrada Tapere)","Bolivar (Rio Apacairao)","Bolivar (Rio Macarupey)")
Tabla6<-data.frame("Plantas"=T6,"Entidad Federal"=T6.1,"Numero de Unidades"=replicate(17,0),"Capacidad Instalada de Generacion de Energia Electrica (MW)"=replicate(17,0) )
#Caracteristicas de los sistemas de fuente alternas de Generacion de energia Electrica Segun tipo,A;o (Tabla I-C.5.)
############## Final de bases de datos para Tab 2
ui <- fluidPage(
dashboardPage(title = "App ", skin="purple",
dashboardHeader(title = "Filter App"),
#Tabla lateral
dashboardSidebar(title="Filtracion de Data",width = 300,
#Primera pestaa
conditionalPanel(condition="input.tabselected==1",
sidebarMenu(
# fontawesome class examples
# https://fontawesome.com/v4.7.0/examples/
# https://fontawesome.com/how-to-use/svg-with-js#additional-styling
# fontawesome site
# https://fontawesome.com/v4.7.0/icons/
# glyphicon site
# https://getbootstrap.com/docs/3.3/components/
# fa-spin class to get any icon to rotate, and use fa-pulse to have it rotate with 8 steps
# just use the icon name without the fa suffix
# add tachometer icon from fontawesome library
fileInput("file","Ingrese el Archivo en formato csv",accept = c("csv",".csv")), # fileinput() function is used to get the file upload contorl option
helpText("Capacidad Maxima: 5 MB",align="center"),
tags$hr(),
h5(helpText("Select the read.table parameters below")),
checkboxInput(inputId = 'header', label = 'Cabecera', value = TRUE),
checkboxInput(inputId = "stringAsFactors", "Caracteres como factores", value = TRUE), #Permite al usuario realizar filtracion multiple
br(),
radioButtons(inputId = 'sep', label = 'Separator',
choices = c(Comma=',',Semicolon=';',Tab='\t'), selected = ','),
tags$hr(),
radioButtons("choice","Elija una opcion", choices=c("Data" =1,"Estructura" = 2,"Resumen" = 3 )),
tags$hr(),
downloadButton('downloadData', 'Descargar'),
br(),
tags$hr()
)
),
#Segunda pestaa
conditionalPanel(condition="input.tabselected==2",
tags$hr(),
selectInput(inputId = "S.Table", label = "Seleccione la tabla a editar",choices = c("II-D.16.","II-D.17.","II-D.18."),selected ="II-D.16." ),
tags$hr(),
radioButtons("choice2","Elija una opcion", choices=c("Histograma" =1,"Grafico circular" = 2,"Grafico" = 3 )),
tags$hr(),
downloadButton("downloadData2", "Descargar tabla en excel (.csv)"),
br(),
tags$hr(),
br()
),
#Tercera pestaa
conditionalPanel(condition="input.tabselected==3","contents",
fileInput("file3","Ingrese el Archivo a editar en formato csv",accept = c("csv",".csv"))
)
),
dashboardBody(shinyjs::useShinyjs(),
#Cuerpo de la aplicacion
fluidRow( tabsetPanel(
#Primera pestaa.
tabPanel("Hola",value=1,
conditionalPanel(condition = "input.choice == 1",
div(style = 'overflow-x: scroll',DT::dataTableOutput("dat",width = "100%") ),
helpText("Numero de fila con observaciones buscadas"),
verbatimTextOutput("filtered_row")
),conditionalPanel(condition = "input.choice ==2",
h4("Estructura de la data Cargada",align="center"),verbatimTextOutput("Estructura")
#Imprime La estructura de la data cargada.
),
conditionalPanel(condition = "input.choice == 3",
h4("Resumen",align="center"),verbatimTextOutput("Resumen")
#Imprime la el resumen de la data cargada
)
),
#segunda pestaa.
tabPanel("Segunda pestaa",value=2,"Hola mundo",
#helpText("editable table"),
div(style = 'overflow-x: scroll',rHandsontableOutput("table")),
br(),br(),
conditionalPanel(condition = "input.choice2 == 1","Hola",plotlyOutput("plot_one")
),
conditionalPanel(condition = "input.choice2 == 2","Hola 2",plotlyOutput("plot_two")),
conditionalPanel(condition = "input.choice2 == 3","Hola 3",
div(style="display:inline-block",uiOutput("varx")),
div(style="display:inline-block",uiOutput("vary")),
plotlyOutput("plot_three")
)
),
tabPanel("Tab 3",value=3,"Hola",
div(style = 'overflow-x: scroll',excelOutput("table_Excel",width = "100%", height = "3000px"))
),
id = "tabselected"
)
)
)
))
server <- function(input, output, session) {
########## TAB 1
data <- reactive({
file1 <- input$file
if(is.null(file1)){return()}
read.table(file=file1$datapath, sep=input$sep, header = input$header, stringsAsFactors = input$stringAsFactors)
})
###############Sujeto a cambios########################
# Display data using DT table and using filter option for column filters
output$dat <- renderDataTable(
datatable(data(), options = list(lenghtMenu = list(c(7, 15, -1),
c('5', '15', 'All')), pageLenght = 15), filter ='top',selection = 'multiple', style = 'bootstrap',editable = TRUE)
#Imprime la data cargada para luego filtrarla
)
#Imprime la estructura de los datos ingresados
output$Estructura <- renderPrint({
str(data())
})
#Imprime el resumen
output$Resumen <- renderPrint({
summary(data())
})
#### Uso de las funciones observeEvent y eventReactive para permitir actualizar de la data editada
#input[["dat_rows_all"]] Filtra la data
##############################Sujeto A cambios##################################
############ Download handler for the download button ####################
# downloadHandler() toma dos argumentos, siendo ambos funciones.
output$downloadData <- downloadHandler(
filename = function() {
paste(input$file, ".csv", sep = "")
},
content = function(file) {
write.csv(data()[input[["dat_rows_all"]], ], file, row.names = FALSE)
# [input[["dat_rows_all"]] se encarga de guardar el archivo filtrado
}
)
#Segunda pestana (Inicio)
######
#Guardas los dataframe
values = reactiveValues()
values[["II-D.16."]] <- Lista
values[["II-D.17."]] <- Tabla4
values[["II-D.18."]] <- Tabla6
observe({
if (!is.null(input$table)) {
temp <- hot_to_r(input$table)
if (isolate(input$S.Table) == "II-D.16.") {
values[["II-D.16."]] <- temp
} else if ( isolate(input$S.Table) == "II-D.17." ) {
values[["II-D.17."]] <- temp
} else if ( isolate(input$S.Table) == "II-D.18." ) {
values[["II-D.18."]] <- temp
}
}
})
#Permite cambiar entre tablas
TablaD<- reactive({
if (input$S.Table == "II-D.16.") {
TablaD <- values[["II-D.16."]]
} else if (input$S.Table == "II-D.17."){
TablaD <- values[["II-D.17."]]
} else if (input$S.Table == "II-D.18."){
TablaD <- values[["II-D.18."]]
}
TablaD
})
I.Plot <- reactive({
if (input$S.Table == "II-D.16.") {
I.Plot <- values[["II-D.16."]]
} else if (input$S.Table == "II-D.17."){
I.Plot <- values[["II-D.17."]]
} else if (input$S.Table == "II-D.18."){
I.Plot <- values[["II-D.18."]]
}
I.Plot
})
output$table <-renderRHandsontable({
if(is.null( TablaD() )){return()}
rhandsontable( TablaD() , showToolbar=TRUE , search=TRUE , rowDrag = TRUE,
columnDrag = TRUE, rowResize = TRUE, minDimension = c(100, 100))
})
#####Guardar cambios para Histograma
# Observa los cambios realizados a las filas para luego actualizar la columna elegida basada en la formula
observeEvent(
input$table$changes$changes, # observe if any changes to the cells of the rhandontable
{
xi=input$table$changes$changes[[1]][[1]] # capture the row which is changed
#datavalues$info <- hot_to_r(input$table) # convert the rhandontable to R data frame object so manupilation / calculations could be done
values <- hot_to_r(input$table)
# Calculating the cell value of column C using cell values in column a and b
# 1 is added to row index because change event row and column indices starts with zero vs R index which starts with 1
#datavalues$info[xi+1,ncol(datavalues$info)] = datavalues$info[xi+1,2] + datavalues$info[xi+1,3]
values[xi+1,ncol(values)] = values[xi+1,2] + values[xi+1,3]
#calculate column variable C values based on cell values in column variable a and b
#Calcula el valor de la ultima columna basado en los valores de las columnas anteriores
}
)
## plot a histogram using plotly
## plotly graph also changes as the table cell values changes
output$plot_one <- renderPlotly({
#plot_ly(data=datavalues$info, x=~Produccion_de_Energia_Neta , type="histogram",marker = list(color =c('green','blue','purple','yellow','black','orange','white','brown','pink','red') ) ) %>%
plot_ly(I.Plot(), x=~Produccion_de_Energia_Neta , type="histogram",marker = list(color =c('green','blue','purple','yellow','black','orange','white','brown','pink','red') ) ) %>%
#x=~Numero_de_Unidades
layout(title="Histograma energia bruta", xaxis=list(title="Valores"),yaxis=list(type='linear'),bargap=0.1)
})
#Agregar colores
#marker = list(color =c('green','blue','purple','yellow','black','orange','white','brown','pink','red') )
####Guardar cambios para Histograma (FIN)
##### Grafico circular
#Produccion.de.Energia.Electrica.Bruta
output$plot_two <-renderPlotly({
plot_ly(
data=I.Plot(),labels=~Plantas, values=~Consumo_Interno_y_perdidas_en_Generacion , type="pie",
#labels=~Plantas
#values=~Numero_de_Unidades
#values=~Produccion_de_Energia_Neta
#values,labels="Cosas", values=~Produccion_de_Energia_Neta , type="pie",
#textposition = 'inside',
#textinfo = 'label',
insidetextfont = list(color = '#FFFFFF'),
hoverinfo = 'text',
text = ~paste(Consumo_Interno_y_perdidas_en_Generacion , ' Khw'),
marker = list(colors = colors,
line = list(color = '#FFFFFF', width = 1)),
#The 'pull' attribute can also be used to create space between the sectors
showlegend = TRUE
) %>% layout(
title = 'Grafico Circular',
xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),
yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE)
)
})
##### Grafico circular (FIN)
####### Grafico Lineal (INICIO)
# Pulling the list of variable for choice of variable x
X.var<-reactive({
output$varx <- renderUI({
selectInput("variablex", "Seleccione la variable X", choices=names(TablaD()))
})
})
# Pulling the list of variable for choice of variable y
Y.var<-reactive({
output$vary <- renderUI({
selectInput("variabley", "Seleccione la variable y", choices=names(TablaD()))
})
})
output$plot_three <-renderPlotly({
plot_ly(data=I.Plot(), x = ~X.var(), y = ~Y.var(), name = 'High 2014', type = 'scatter', mode = 'lines',
#x = ~Produccion_de_Energia_Neta, y = ~Produccion_de_Energia_Neta
line = list(color = 'rgb(205, 12, 24)', width = 4)) %>%
layout(title = "Grafico Lineal",
xaxis = list(title = "Valores"),
yaxis = list (title = "Kwh"))
})
###### Grafico Lineal (FIN)
############ Download Handler 2 #######################
# downloadHandler() toma dos argumentos, siendo ambos funciones.
output$down <- downloadHandler(
filename = function() {
paste(input$file, ".csv", sep = "")
},
content = function(file) {
write.csv(data2(), file, row.names = FALSE)
# [input[["data.frame_rows_all"]] se encarga de guardar el archivo filtrado
}
)
#Segunda pestana (Final)
#################################
#################################
#Tercera Pestana (Inicio)
################################
################################
##### Tab that allows the user to upload and edit an excel file using the excelR
data3 <- reactive({
file_excel <- input$file3
if(is.null(file_excel)){return()}
read.table(file=file_excel$datapath, sep=input$sep, header = input$header, stringsAsFactors = input$stringAsFactors)
})
output$table_Excel <-renderExcel({
if(is.null( data3() )){return()}
excelTable( data3() , showToolbar=TRUE, autoColTypes=TRUE,allowComments=TRUE , search=TRUE ,fullscreen = FALSE, rowDrag = TRUE,
columnDrag = TRUE, rowResize = TRUE, minDimension = c(100, 100))
})
#Tercera Pestana (Final)
###############################
###############################
}
shinyApp(ui, server)