Reputation: 41
I would like to know how to update a global variable by calling a function and return it. Here is my brief code from 'server.R'. My ui.R consists of several lines of code to display the output.
sentence <- ""
result <- c()
updateSen <- function(input){
print("function executed!")
if(length(sentence) == 0){
result <<- c(result, "First")
sentence <<- paste(sentence, input, sep = " ")
}else{
result <<- c(result, input)
sentence <<- paste(sentence, input, sep = " ")
}
}
shinyServer(
function(input, output){
word <- reactive({
word <- input$tid
})
output$oid <- renderText({
paste(input$tid)
})
output$sen <- renderText({
updateSen(word())
sentence
})
}
)
What I would like to do with the code above is this... 1. Ask user to type a word 2. make a sentence with a word user typed 3. run a function 4. display a sentence
However, it seems like it doesn't work well and there are many things I don't know what's going on. First of all, I have no idea why updateSen() function is called a lot of times during the program execution. Second, the global variable 'result' does not change after the first execution. I would like this variable to be updated.
Upvotes: 1
Views: 2222
Reputation: 45
From what I understand, the variable 'result' will start changing automatically once you apply reactive keyword. Try
updateSen <- reactive(function(input){
print("function executed!")
...
}
})
Secondly, I think you should not have variables like sen
and result
as 'global' rather you should work with textInput()
function and variables like input$sentence
.
I suggest you read more about reactive variables and functions in Shiny.
Upvotes: 1