R: Select option 引入一个数字

R: Select option by introducing a number

我想构建一个非常简单、粗略的函数,您可以在其中引入一个词(西班牙语)并获得最可行的下一个词(一种文本预测器)。所以当用户介绍me时,建议是hahelodagusta。现在,我想让用户通过键入 1、2、3、4 或 5 来 select 这五个建议之一。在 R 中有什么方法可以做到这一点吗?

predictor<-function(){
  word<-readLines(stdin(),n=1)
  words<-sort(table[first==word],decreasing=TRUE)[2:6]
  suggestions<-gsub(".* ","",names(words))
  return(suggestions)
}

#table = table with unigram and bigram frequencies of a corpus
#first = vector with the first word in each bigram

> predictor()
me
[1] "ha"    "he"    "lo"    "da"    "gusta"

如果是列表,你可以试试:

predictor[1]

这将提取第一个元素(“ha”)。

您已经提示用户输入一次。你可以再做一次以获得你想要获得的项目的数量。但是您必须以允许用户选择的方式打印建议。

predictor = function(){
  ### Since I have neither the table nor the list, I just made a makeshift words vector
  words = c("ha","he","lo","da","gusta")
  names(words)=words
  
  suggestions<-paste(1:length(words),names(words),sep=": ")
  print(paste("Possible Words:",paste(suggestions,collapse="; ")))
  print("Please enter a number to select:")
  #input = scan("",what="character",n=1)
  input<-readLines(stdin(),n=1)
  print(paste("You selected Item #",input,": ",names(words)[as.integer(input)],sep=""))
}

这将为您提供输出:

[1] "Possible Words: 1: ha; 2: he; 3: lo; 4: da; 5: gusta"
[1] "Please enter a number to select:"
4
[1] "You selected Item #4: da"