简体   繁体   English

Rcpp-如何从Shiny中的Rcpp函数调用R函数

[英]Rcpp - how to call R function from Rcpp function in Shiny

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" . 我只是rcpp的新手,我的rcpp函数有问题,当我直接运行App时,程序显示错误找不到函数“ krit” but when i run the function partially with CTRL+R and then run App the program is running well. 但是,当我使用CTRL + R部分运行该功能,然后运行App时,程序运行良好。 is there a code for call R function from rcpp function in shiny that i must not run the function partially? 有光泽的rcpp函数调用R函数的代码,我不能部分运行该函数吗? in other words, when i directly run App the shiny will running well. 换句话说,当我直接运行App时,它将运行良好。 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 UI

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

    ),
    mainPanel(

      uiOutput("testing")
    )
  )
))

This is a scoping issue regarding how shiny and Rcpp view the different environments. 这是关于shinyRcpp如何查看不同环境的范围问题。

What's happening is an issue with accessing the global environment using... 发生的事情是使用...访问全局环境的问题。

1) Standard Rcpp::Function magic 1)标准Rcpp::Function魔术

Rcpp::Function krit("krit");

2) Rcpp::Environment with a global pull yields a missing value. 2)具有全局拉动的Rcpp::Environment产生缺少的值。

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])' file3d3f43b856e05.cpp:9:45:错误:与“(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. 因此,解决此范围问题的最佳方法是将要使用的R函数传递给已编译的C ++函数并对其进行调用。 eg 例如

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

Or, you will need to modify the server.R to: 或者,您将需要将server.R修改为:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM