【问题标题】:Rcpp - how to call R function from Rcpp function in ShinyRcpp - 如何在 Shiny 中从 Rcpp 函数调用 R 函数
【发布时间】:2016-05-01 17:56:42
【问题描述】:

我刚接触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")
    )
  )
))

【问题讨论】:

标签: c++ r shiny rcpp


【解决方案1】:

这是一个关于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))
    )
  })

}) 

因此,您应该得到:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-25
    • 1970-01-01
    • 2013-11-13
    • 1970-01-01
    • 1970-01-01
    • 2019-01-17
    • 2021-01-05
    相关资源
    最近更新 更多