Transform a R base code into a Shiny app, problems with the parameters of functions

Hello, I have a code that perfectly works.
I use an csv file to load the data and transform it as a data frame.
I have checked how to create a shiny app, and I have put the inputs of the functions in the ui part.
For example, I wrote:
numericInput(
inputId = "ni",
label = "Número de instrumentos:",
min = 1,
max = 10,
value = 2),
the same with the others parameters.
So, in the server part I wrote that input as:
ni <-reactive(input$ni)
Whitout the reactive, I get an error. And everything works well!

The problem is that when I try to use those parameters in a function (how it worked before as a simple code) like:
tiie(datos = data,pilar=pila,inicio = input$ini,convencion = conv, indicadora = indi, plazopagos = ppf)
I get errors! :frowning:
Error in datos$fecha : object of type 'closure' is not subsettable

I have checked about that error, is related about if I try to use a variable like a data frame or something like that.
I imagine that the problem is in this line, inside of the function:
renglon<-which(datos$fecha==inicio)

I don't know what happen, or how do I could fix this.
I only want to transform the parameters into an input and then use them in the rest of the code as before. :confused:
Help please.

By the way, if I write:
tiie(datos = data,pilar=pila,inicio = ini,convencion = conv, indicadora = indi, plazopagos = ppf)
I get:
Error in matchSignature(signature, fdef) :
more elements in the method signature (2) than in the generic signature (1) for function ‘asJSON’

if data is reactive then you would reference it with data()
but this is a guess because you don't provide the minimal code to understand your issue.
See this guide for help in getting the best help, and good luck
FAQ: How to do a minimal reproducible example ( reprex ) for beginners

The problem that I found is related to the data, it looks like it doesn't recognize the data as a data frame.

For example, I get an error with this:
renglon<-which(data$fecha==ini)
Error in ==.default(parswap$fecha, ini) :
comparison (1) is possible only for atomic and list types

Do I have to convert data to a reactive object?? :o

where ini is:
ini <-reactive(input$ini)

if ini is what you say it is, then when you wish to use it, you would use ini()
(or dont bother and use input$ini directly).
the shiny documentation on this is quite good I think, have you worked through the examples ?
if you want specific help with your specific issues you should make a small effort and provide a reprex.

im afraid this is neither a reprex nor a minimal reprex.
a read.csv function is not reproducible sharing of data.
far too much code is being offered than in principle would be needed to test and understand the basic principles of reactivity and how to pass reactives into functions etc.
please slim your code so that you can learn from the answer rather than having intent for someone to completely repair your entire project (which is impossible without data / see lack of alternative offered for read.csv provided).

I understand, maybe this would be better:

parswap<-read.csv("datosC.csv")
colnames(parswap)<-c("fecha","3X1","13X1","52X1","130X1","156X1")
parswap$fecha<-as.character(parswap$fecha)
parswap$fecha<-as.Date(parswap$fecha,format="%d/%m/%Y")
parswap<-as.data.frame(parswap)

In the server part:

ini <-reactive(input$ini) #fecha de valoración del portafolio "YYYY-MM-dd"
ni <-reactive(input$ni) #número de instrumentos que constituyen el portafolio
ppf <-28 #frecuencia de pagos de flujos ambas patas
conv<-360
indi<-0
pila<-"3X1"

tiie<-function(datos,pilar,inicio,convencion,indicadora,plazopagos){
renglon<-which(datos$fecha==inicio)
}

fdesc <-tiie(datos = parswap,pilar=pila,inicio = ini,convencion = conv, indicadora = indi, plazopagos = ppf)

And I get:
Error in ==.default(datos$fecha, inicio) :
comparison (1) is possible only for atomic and list types

I think that the problem is this line:
renglon<-which(datos$fecha==inicio)

I don't know what happened, as a simple R code it works :confused:
Thank you!

first I'll critique the attempt at reprex, as it is not a reprex, which you can understand because in principle it is not runnable if pasted into a fresh session of R, then I'll continue to see if I can spot any obvious issue (without having access to your reprex)

critique:

... no

id prefer for you to provide an actual small server definition

ok now heres one obvious issue

fdesc <-tiie(datos = parswap,pilar=pila,inicio = ini,convencion = conv, indicadora = indi, plazopagos = ppf)

ini has been defined as reactive so as relates to passing it into tiiie it should be ini()

fdesc <-tiie(datos = parswap,pilar=pila,inicio = ini(),convencion = conv, indicadora = indi, plazopagos = ppf)

I really appreciate your help, I understand.
I can't upload the csv file, but maybe I could post some of the data as an example.
"fecha" "3X1"

27/04/2020 0.047757121
28/04/2020 0.046469264
29/04/2020 0.045594935
30/04/2020 0.046422991
04/05/2020 0.046384532
05/05/2020 0.046285446
06/05/2020 0.04542063
07/05/2020 0.043825089
08/05/2020 0.042658616
11/05/2020 0.044523176
12/05/2020 0.043061725
13/05/2020 0.044521232
14/05/2020 0.044438627

And ini is declared as: dateInput(
inputId = "ini",
label = "Selecciona la fecha:",
value = "2020-05-13"
),

And I make it reactive in the server part because, without, I get an error.

I changed what you said @nirgrahamuk, wrote ini() into the function.
But doesn't work :confused:
Now I get:
Error in .getReactiveEnvironment()$currentContext() :
Operation not allowed without an active reactive context. (You tried to do something that can only be done from inside a reactive expression or observer.)

Thanks!

theres a fundamental problem in our communication, and its that I think you haven't taken a deep breath and read the recommended link on how to reprex.
You should understand, I cant copy and paste and immediately have your dataframe as a result, of you are pasing arbitrary table formatted text to the forum.
You should learn the use of dput() this is discussed in the linked article.
when sharing code to the forum, you should use triple backticks to format the code as code like this
```

it looks good

```
back to normal.

finally, reactive code can run inside reactive contexts, this is impossible to determine without your having shared a reprex, (i.e. complete code) as I can't determine the context.
you could as a hack, wrap the entire code block of concern inside an isolate. i.e.

isolate({ your block of code here})

but doing so is likely a misunderstanding of the reactive framework, you should not confuse traditional plain functions, with reactive functions. you typically want your plain functions wrapped by reactive ones, so that the inputs cause recalculation on an reactive basis and the output can be treated as reactive, I'm guessing that you are just using a plain function in a plain context but trying to send reactive inputs to it, which causes your issues.

the code looks much better and shorter, but you pasted an image of the code that would produce some example data rather than code... so please correct that.

output$f should be an appropriate render function,...

par<-tibble::tribble(
             ~fecha,      ~`3X1`,
       "27/04/2020", 0.047757121,
       "28/04/2020", 0.046469264,
       "29/04/2020", 0.045594935,
       "30/04/2020", 0.046422991,
       "04/05/2020", 0.046384532,
       "05/05/2020", 0.046285446,
       "06/05/2020",  0.04542063,
       "07/05/2020", 0.043825089,
       "08/05/2020", 0.042658616,
       "11/05/2020", 0.044523176,
       "12/05/2020", 0.043061725,
       "13/05/2020", 0.044521232,
       "14/05/2020", 0.044438627
       )

colnames(par)<-c("fecha","3X1")
par$fecha<-as.character(par$fecha)                     
par$fecha<-as.Date(par$fecha,format="%d/%m/%Y")
par<-as.data.frame(par)

library(shiny)

# Define UI for application that draws a histogram
ui <- fluidPage(
   
   # Application title
   titlePanel("Example"),
   
   # Sidebar with a slider input for number of bins 
   sidebarLayout(
      sidebarPanel(
         
         dateInput(                                      
           inputId = "ini",                              
           label = "Selecciona la fecha de valoración:",
           value = "2020-05-13"
         )
      ),
      
      # Show a plot of the generated distribution
      mainPanel(
        verbatimTextOutput(           #inprime un dato en formato de codigo
          outputId = "f")
      )
   )
)

# Define server logic required to draw a histogram
server <- function(input, output) {
   
  ini <-reactive(input$ini) #fecha seleccionada  "YYYY-MM-dd"
  ppf <-28 
  pila<-"3X1"
  indi<-0 
  conv<-360  
  tiie<-function(datos,pilar,inicio,convencion,indicadora,plazopagos){  
      renglon<-which(datos$fecha==inicio)
  }
  
  fdesc <-tiie(datos = par,pilar=pila,inicio = ini,convencion = conv, indicadora = indi, plazopagos = ppf) 
  output$f<-fdesc
}

# Run the application 
shinyApp(ui = ui, server = server)


The problem is:
Error in ==.default (datos$fecha, inicio) :
comparison (1) is possible only for atomic and list types

I think that the problem is in the line:
which(datos$fecha==inicio)

With: output$f<-fdesc I try to visualize the result of the function, but I don't know if this the best way to do that. Only that matter is make the function works in a shiny environment.
Thank you for all!

it works now

par <- tibble::tribble(
  ~fecha, ~`3X1`,
  "27/04/2020", 0.047757121,
  "28/04/2020", 0.046469264,
  "29/04/2020", 0.045594935,
  "30/04/2020", 0.046422991,
  "04/05/2020", 0.046384532,
  "05/05/2020", 0.046285446,
  "06/05/2020", 0.04542063,
  "07/05/2020", 0.043825089,
  "08/05/2020", 0.042658616,
  "11/05/2020", 0.044523176,
  "12/05/2020", 0.043061725,
  "13/05/2020", 0.044521232,
  "14/05/2020", 0.044438627
)

# colnames(par)<-c("fecha","3X1") # does nothing....
# par$fecha<-as.character(par$fecha)  # does nothing
par$fecha <- as.Date(par$fecha, format = "%d/%m/%Y")
# par<-as.data.frame(par) # whats wrong with a tibble ?

library(shiny)

# Define UI for application that draws a histogram
ui <- fluidPage(
  
  # Application title
  titlePanel("Example"),
  
  sidebarLayout(
    sidebarPanel(
      dateInput(
        inputId = "ini",
        label = "Selecciona la fecha de valoración:",
        value = "2020-05-13"
      )
    ),
    
    mainPanel(
      verbatimTextOutput( 
        outputId = "f"
      ))))


server <- function(input, output) {
  ini <- reactive(input$ini) # fecha seleccionada  "YYYY-MM-dd"
  ppf <- 28
  pila <- "3X1"
  indi <- 0
  conv <- 360
  tiie <- function(datos, pilar, inicio, convencion, indicadora, plazopagos) {
    renglon <- which(datos$fecha == inicio)
  }
  
  fdesc <- reactive({
    tiie(datos = par, pilar = pila, inicio = ini(), convencion = conv, indicadora = indi, plazopagos = ppf)
  })
  
  output$f <- renderText({
    fdesc()
  })
}

# Run the application
shinyApp(ui = ui, server = server)
1 Like

Thank you for your time, especially for your patience!!

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.