I'm using fileInput to upload a file that is needed to be edited and then creating a workbook, which needs to be downloaded. Getting the error: "Operation not allowed without an active reactive context. You tried to do something that can only be done from inside a reactive expression or observer" I updated the code by the answers from other question.
Why do I still get this error?
server <- function(input, output) {
mydata = reactive({
req(input$dat)
read_excel(input$dat$datapath, col_names = FALSE)
})
mydat <- reactive({
mydata <- mydata()
mydata <- mydata[-(1:2),]
names(mydata) <- mydata[1,]
mydata <- mydata[-1,]
mydata <- mydata[,-1]
mydata <- data.frame(mydata)
})
func <- function(d){
x <- na.omit(as.numeric(d))
mean <- mean(as.numeric(x), na.rm=T)
sd <- sd(as.numeric(x), na.rm=T)
Tmin <- mean - (3*sd)
Tmax <- mean + (3*sd)
return(x[which(x < Tmin | x > Tmax)])
}
red_style <- createStyle(fgFill="#FF0000")
out <- reactive({apply(mydat(), 1, func)})
w <- reactive({
w <- createWorkbook()
addWorksheet(w, sheetName="Data")
writeData(w, sheet="Data", x=mydat())
})
seq <- 1:nrow(mydat())
for(i in seq){
if(length(func(mydat()[i,]))>0) {
yB <- as.matrix(which(str_extract(mydat()[i,3:ncol(mydat())], '\\d+.\\d{2}') %in%
str_extract(as.character(out()[[i]]), '\\d+.\\d{2}'), arr.ind=TRUE))
yB <- yB + 2
addStyle(w(), sheet="Data", style = red_style, cols=yB, rows=i+1)
}
}
output$download <- downloadHandler(
filename = function() {
paste0("Data-", Sys.Date(), ".xlsx")
},
content = function(file){
saveWorkbook(w(), file, overwrite=TRUE)
}
)}