Im writing a function to incorporate into shiny app that predicts the next word from a set of pre defined files. When I create the functions to predict the next word using ngrams,
I'm running into this error
x object of type 'closure' is not subsettable
i Input ..1 is top_n_rank(1, n).
Run rlang::last_error() to see where the error occurred.
In addition: Warning message:
In is.na(x) : is.na() applied to non-(list or vector) of type 'closure'
This is my R program. I have already created bi-gram tri-gram and quad-gram words in another R script and saved it as rds files which I have used here
library(tidyverse)
library(stringr)
library(dplyr)
library(ngram)
library(tidyr)
bi_words <- readRDS("./bi_words.rds")
tri_words <- readRDS("./tri_words.rds")
quad_words <- readRDS("./quad_words.rds")
bigram <- function(input_words){
num <- length(input_words)
dplyr::filter(bi_words,
word1==input_words[num]) %>%
top_n(1, n) %>%
filter(row_number() == 1L) %>%
select(num_range("word", 2)) %>%
as.character() -> out
ifelse(out =="character(0)", "?", return(out))
}
trigram <- function(input_words){
num <- length(input_words)
dplyr::filter(tri_words,
word1==input_words[num-1],
word2==input_words[num]) %>%
top_n(1, n) %>%
filter(row_number() == 1L) %>%
select(num_range("word", 3)) %>%
as.character() -> out
ifelse(out=="character(0)", bigram(input_words), return(out))
}
quadgram <- function(input_words){
num <- length(input_words)
dplyr::filter(quad_words,
word1==input_words[num-2],
word2==input_words[num-1],
word3==input_words[num]) %>%
top_n(1, n) %>%
filter(row_number() == 1L) %>%
select(num_range("word", 4)) %>%
as.character() -> out
ifelse(out=="character(0)", trigram(input_words), return(out))
}
ngrams <- function(input){
# Create a dataframe
input <- data.frame(text = input)
# Clean the Inpput
replace_reg <- "[^[:alpha:][:space:]]*"
input <- input %>%
mutate(text = str_replace_all(text, replace_reg, ""))
# Find word count, separate words, lower case
input_count <- str_count(input, boundary("word"))
input_words <- unlist(str_split(input, boundary("word")))
input_words <- tolower(input_words)
# Call the matching functions
out <- ifelse(input_count == 1, bigram(input_words),
ifelse (input_count == 2, trigram(input_words), quadgram(input_words)))
# Output
return(out)
}
input <- "In case of a"
ngrams(input)
Perhaps the missing step here is counting which ngram in each case is the most common before selecting the top one. A simple solution would be to substitute in
add_count
instead oftop_n
:... as the centre part of your quadgram call. The call to
word4
counts the most frequent 4th word after filtering for words 1-3. Thesort = TRUE
argument makes the top-frequency quadgram appear in row 1, which your next line is then selecting for. Hope this is a helpful step - do follow up with any questions or corrections or mark as done if this solves this particular problem.