我从文件上传小部件(reactive
)获取输入数据,如:
第1步 getData <- reactive(...) #psuedo code
。
我需要对数据做一些工作并以某种方式存储结果:
第2步 result #SOMEHOW# = Clean1(getData()) #psuedo code
。
最后我将渲染结果如下:
第3步 output$DataAfter = renderTable({ result... }) #psuedo code
。
我该怎么做第2步?我尝试了result = reactive({ Clean1(getData()) })
,但是出现错误:在我上传文件之前输入为class NULL
。
以下代码,我将Clean1()
功能放在第1步 getData()
ui.R
library(shiny)
shinyUI(fluidPage(
titlePanel("Uploading Files"),
sidebarLayout(
sidebarPanel(
fileInput('file1', 'Choose CSV File',
accept=c('text/csv',
'text/comma-separated-values,text/plain',
'.csv')),
tags$hr()
),
mainPanel(
tableOutput('DataBefore'),
tableOutput('DataAfter'),
tableOutput('Aggregation')
)
)
))
server.R
library(shiny)
library(dplyr)
library(stringr)
library(stringdist)
library(qdapRegex)
source('Clean1.R')
shinyServer(function(input, output) {
getData <- reactive({
inFile <- input$file1
if (is.null(inFile)) return(NULL)
Clean1( read.csv(inFile$datapath) )
})
output$DataAfter = renderTable({
as.data.frame( getData()[[1]] )
})
output$Aggregation = renderTable({
as.data.frame( getData()[[2]] )
})
})
Clean1.R
Clean1 = function(data){
data = data %>% sample_frac(1)
data = data %>%
mutate_each(funs(toupper)) %>%
mutate_each(funs(gsub("[[:punct:]]", " ", .))) %>%
mutate_each(funs(str_trim)) %>%
mutate_each(funs(rm_white))
by.town = data %>%
group_by(State, Town) %>%
summarise( Count = n() )
return(list(data, by.town))
}
现在我将结果存储为:result = reactive({ Clean1(getData()) })
,并且在我上传文件之前显示错误(最后仍然有效)。
错误是
Don't know how to sample from objects of class NULL
此错误应发生在Clean1()
的开头。我上传之前似乎认为getData()
是NULL
。
UI。 R和Clean1.R不会改变。
server.R
library(shiny)
library(dplyr)
library(stringr)
library(stringdist)
library(qdapRegex)
source('Clean1.R')
shinyServer(function(input, output) {
getData <- reactive({
inFile <- input$file1
if (is.null(inFile)) return(NULL)
read.csv(inFile$datapath)
})
result = reactive({
Clean1(getData())
})
output$DataAfter = renderTable({
as.data.frame( result()[[1]] )
})
output$Aggregation = renderTable({
as.data.frame( result()[[2]] )
})
})
那么第2步的标准方法是什么?请告诉我。非常感谢!
答案 0 :(得分:1)
代码首次评估时getData()
为NULL
,因此错误有意义。您可以使result
成为由观察者监控的无功值,但我认为这将超出必要的工作量。如果您希望它不显示错误,请尝试将Clean1
包装在tryCatch
块中,以便在出错时返回NULL
。
result = reactive({
tryCatch({
Clean1(getData())
}, error=function(e) NULL)
})