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

标签 c++ r shiny rcpp

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

服务器

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

})

用户界面

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

}) 

因此,你应该得到:

shiny_text

关于c++ - Rcpp - 如何在 Shiny 中从 Rcpp 函数调用 R 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36969986/

相关文章:

r - Shiny 的observeEvent 在应用程序启动时触发

c++ - Haxe C++ 目标中的 Neko Dll

c++ - 使用 QXmlStreamReader C/Qt 解析 XML 文件

c++ - 为什么将单位矩阵等同于 OpenCV 中的变换矩阵

c++ - 从 C++ 代码运行 SQL Server 的存储过程

r - 组织子组字符串(文本)

r - 更改输入时 Shiny 抛出警告 : Error in : Can't extract columns that don't exist

r - 如何使用 R 中的 ggplot 绘制多个物种的平均 CPUE

java - 安装 JGR 时遇到问题

javascript - 在 R Shiny 中使用本地文件 javascript 的 hcmap