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

Rcpp - how to call R function from Rcpp function in Shiny

我刚接触rcpp,我的rcpp函数有问题,当我直接运行 App时,程序显示错误找不到函数"krit"。但是当我 运行 部分功能与 CTRL+R 然后 运行 App 程序是 运行 宁好。是否有从 rcpp 函数调用 R 函数的代码,我不能 运行 部分函数?换句话说,当我直接 运行 App 时,闪亮的 运行 会很好。这是示例代码...

服务器

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")
    )
  )
))

这是关于 shinyRcpp 如何看待不同环境的范围界定问题。

发生的是使用...访问全局环境的问题

1) 标准 Rcpp::Function 魔法

Rcpp::Function krit("krit");

2) Rcpp::Environment 全局拉动产生缺失值。

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

错误:

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

因此,解决此范围问题的最佳方法是将要使用的 R 函数传递到已编译的 C++ 函数中并调用它。例如

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

或者,您需要将 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))
    )
  })

}) 

因此,你应该得到: