我正在尝试自动编辑csv。我希望Shiny应用程序的用户能够在他们的csv中选择他们想要清理的选项。为了澄清,我希望他们能够单击一个按钮,然后更新csv,然后单击另一个按钮并再次更新,同时保持原始更新。目前,我只关注两个按钮的情况,首先我点击“加载”按钮加载并查看csv;然后我想点击“电子邮件清理”按钮添加一列新的已清理电子邮件。最终,我想添加更多按钮。
我的代码目前因错误而崩溃:
.getReactiveEnvironment()$ currentContext()中的错误: 没有活动的反应上下文,不允许操作。 (你试图做一些只能在反应式表达式或观察者内部完成的事情。)
我的代码如下:
UI
ui = fluidPage(
sidebarPanel(
fileInput('file1', 'Choose file to upload',accept = c('text/csv','text/comma-separated-values','text/tab-separated-values','text/plain','.csv','.tsv')),
checkboxInput('header', 'Header', TRUE),
radioButtons('sep', 'Separator',c(Comma=',',Semicolon=';',Tab='\t'),'Comma'),
radioButtons('quote', 'Quote',c(None='','Double Quote'='"','Single Quote'="'"),'Double Quote'),
actionButton("Load", "Load File"),
actionButton("Email", "Clean Email")),
mainPanel(tableOutput("my_output_data"))
)
服务器
server = function(input, output) {
###Load CSV File
data1 <- reactive({
if(input$Load == 0){return()}
inFile <- input$file1
if (is.null(inFile)){return(NULL)}
isolate({
input$Load
my_data <- read.csv(inFile$datapath, header = input$header,sep = input$sep, quote = input$quote,stringsAsFactors =FALSE)
})
my_data
})
output$my_output_data <- renderTable({data1()},include.rownames=FALSE)
data2 <- reactive({
if(input$Email == 0){return()}
inFile <- input$file1
if (is.null(inFile)){return(NULL)}
isolate({
input$Email
my_data <- read.csv(inFile$datapath, header = input$header,sep = input$sep, quote = input$quote,stringsAsFactors =FALSE)
###CLEAN EMAIL BUTTON FORMULA
email_clean <- function(email, invalid = NA)
{
email <- trimws(email)
email[(nchar(email) %in% c(1,2)) ] <- invalid
email[!grepl("@", email)] <- invalid
bad_email <- c("\\@no.com", "\\@na.com","\\@none.com","\\@email.com",
"\\@noemail.com", "\\@directcapital.com", "\\@test.com",
"noemail")
pattern = paste0("(?i)\\b",paste0(bad_email,collapse="\\b|\\b"),"\\b")
email <-gsub(pattern, invalid, sapply(email,as.character))
unname(email)
}
Cleaned_Email <- email_clean(my_data$Email)
my_data<-cbind(my_data,Cleaned_Email)
})
my_data},
{
if(input$Load == 0){return()}
inFile <- input$file1
if (is.null(inFile)){return(NULL)}
isolate({
input$Load
my_data <- read.csv(inFile$datapath, header = input$header,sep = input$sep, quote = input$quote,stringsAsFactors =FALSE)
})
my_data}
)
output$my_output_data <- renderTable({data2()},include.rownames=FALSE)
}
shinyApp(ui = ui, server = server)
谢谢!