我对Shiny很新,我正在尝试传递一个在数据框中创建旧括号的函数,我在Shiny外面测试了一个闪亮的应用程序。
以下是Shiny外面的代码:
# Regular R Code
Aging <- function(data, Transaction.Date){
if(missing(Transaction.Date)) stop("You forgot to specify Transaction Date")
Transaction.Date <- deparse(substitute(Transaction.Date))
data$year <- year(data[,Transaction.Date])
data$Age <- car::recode(year(data[,Transaction.Date]), "year(Report.Date) = year(Report.Date); year(Report.Date)-1 = year(Report.Date)-1; else = paste(year(Report.Date)-2, 'And Prior')")
return(data)
}
Debtors <- data.frame(Names = c("John", "Mary", "Charles", "Peter", "David", "Fabian", "Aggrey", "Elizabeth", "Anthony", "Catherine"), Amount = seq(from = 100000, by = 600, length.out = 10), Transaction.Date = seq.Date(from = as.Date("2016/1/1"), by = "quarter", length.out = 10))
Report.Date <- max(Debtors$Transaction.Date)
Aged.Data <- Aging(Debtors, Transaction.Date)
以下是我试图创建但不起作用的Shiny App:
library(shiny)
Aging <- function(data, Transaction.Date){
if(missing(Transaction.Date)) stop("You forgot to specify Transaction Date")
Transaction.Date <- deparse(substitute(Transaction.Date))
data$year <- year(data[,Transaction.Date])
data$Age <- car::recode(year(data[,Transaction.Date]), "year(Report.Date) = year(Report.Date); year(Report.Date)-1 = year(Report.Date)-1; else = paste(year(Report.Date)-2, 'And Prior')")
return(data)
}
ui <- fluidPage(
dataTableOutput("Aged.Data")
)
server <- function(input, output) {
Data <- reactive({
Debtors <- data.frame(Names = c("John", "Mary", "Charles", "Peter", "David", "Fabian", "Aggrey", "Elizabeth", "Anthony", "Catherine"), Amount = seq(from = 100000, by = 600, length.out = 10), Transaction.Date = seq.Date(from = as.Date("2016/1/1"), by = "quarter", length.out = 10))
Report.Date <- max(Debtors$Transaction.Date)
Aged.Data <- Aging(Debtors, Transaction.Date)
})
output$Aged.Data <- renderDataTable(Data())
}
shinyApp(ui, server)
我得到的错误是:
in recode term: else = paste(year(Report.Date)-2, 'And Prior')
message: Error in year(Report.Date) : object 'Report.Date' not found
我真的很感激任何帮助。
约瑟夫。
答案 0 :(得分:1)
这是一个简单的范围问题。
闪亮示例中的Aging
函数位于全局范围内,它指的是Report.Date
。范围方面,Report.Date
只能在Aging
中访问,如果它在函数本身中定义或者它也是全局变量。在非闪亮的例子中就是这种情况。
但在您的闪亮版本中,变量仅在server
函数内定义。 Aging
和server
不会共享任何变量。所以错误确实是,从全局范围的角度来看,Report.Date
不存在。
这里至少有三个选项:
Aging
功能移至server
功能(作为子功能),以便Aging
可以访问server
的范围。Report.Date
范围从server
范围移到全局范围内,并使用server
而不是<<-
从<-
更改它。 (用于在超范围内分配变量的键。)Report.Date
成为参数,而不是超出范围的变量。然后,在server
内,您可以使用所需的值Report.Date
基于这个简单的例子,我会说第三个解决方案是最干净的。
如果您需要更多解释,请随时发表评论。