# Load necessary libraries
library(shiny)
library(dplyr)
##
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
##
## filter, lag
## The following objects are masked from 'package:base':
##
## intersect, setdiff, setequal, union
library(stringr)
# Load or create a pre-trained n-gram model
# Replace this placeholder with your trained model or data
# For demonstration purposes, we create a dummy n-gram dataset
ngram_data <- data.frame(
phrase = c("how are", "how is", "how do", "what is", "what are"),
prediction = c("you", "it", "we", "this", "they"),
stringsAsFactors = FALSE
)
# Define UI
ui <- fluidPage(
titlePanel("Next-Word Prediction App"),
sidebarLayout(
sidebarPanel(
textInput("phrase", "Enter a phrase:", ""),
actionButton("predict", "Predict Next Word")
),
mainPanel(
h4("Prediction"),
verbatimTextOutput("outputPrediction")
)
)
)
# Define server
server <- function(input, output) {
# Reactive expression for prediction
predict_next_word <- reactive({
req(input$phrase) # Ensure input is provided
phrase <- tolower(str_trim(input$phrase))
match <- ngram_data %>%
filter(str_detect(phrase, paste0("^", phrase))) %>%
slice(1) # Take the first match
if (nrow(match) > 0) {
match$prediction
} else {
"No prediction available"
}
})
# Output prediction
output$outputPrediction <- renderText({
input$predict # Trigger on button click
isolate(predict_next_word())
})
}
# Run the application
shinyApp(ui = ui, server = server)
Shiny applications not supported in static R Markdown documents