1

i just new with rcpp, i have a problem with my rcpp function, when i directly run App, the program display error could not find function "krit". but when i run the function partially with CTRL+R and then run App the program is running well. is there a code for call R function from rcpp function in shiny that i must not run the function partially? in other words, when i directly run App the shiny will running well. this is the example code...

server

library(shiny)
library(Rcpp)
krit <- function(n){
  mat <- matrix(1,n,1)
  return(mat)
}
cppFunction('
            NumericMatrix tes1(int n){
            Function krit("krit");
            NumericMatrix test = krit(n+1);
            return(test);
            }
            ')

shinyServer(function(input, output) {

  output$testing <- renderUI({
    list(
    renderPrint(tes1(3))
    )
  })

})

ui

library(shiny)
shinyUI(fluidPage(
  titlePanel("Shiny Text"),
  sidebarLayout(
    sidebarPanel(

    ),
    mainPanel(

      uiOutput("testing")
    )
  )
))
2

1 Answer 1

3

This is a scoping issue regarding how shiny and Rcpp view the different environments.

What's happening is an issue with accessing the global environment using...

1) Standard Rcpp::Function magic

Rcpp::Function krit("krit");

2) Rcpp::Environment with a global pull yields a missing value.

Rcpp::Environment env = Environment::global_env();
Rcpp::Function krit = env("krit");

Error:

file3d3f43b856e05.cpp:9:45: error: no match for call to '(Rcpp::Environment) (const char [5])'

Thus, the best that can be done to resolve this scoping issue is to pass the R function that you want to use into the compiled C++ function and call it. e.g.

NumericMatrix tes1(int n, Rcpp::Function krit)

Or, you will need to modify the server.R to:

library(shiny)
library(Rcpp)

krit <- function(n){
  mat <- matrix(1,n,1)
  return(mat)
}

cppFunction('
            // Added krit as a function pass
            NumericMatrix tes1(int n, Rcpp::Function krit){
            NumericMatrix test = krit(n+1);
            return(test);
            }
            ')

shinyServer(function(input, output) {

  output$testing <- renderUI({
    list(
      # Added parameter to `tes1` to pass in krit.
      renderPrint(tes1(n = 3, krit = krit))
    )
  })

}) 

Thus, you should get:

shiny_text

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.