我如何获取用户从样本中选择的值?

How can I take values a user selects from a sample?

我有一个由“Rolls<-sample(1:6, 5, replace=TRUE)”给出的掷骰样本

我想做的是要求用户 select 样本中的两个值,然后我希望将这两个值相加并存储在样本中。 (我不需要对加法中使用的值进行任何处理)

我的主要问题是我一直在使用:

"first_number <- readline(prompt="请输入您要添加的第一个值:")"("second_number"也是如此)

这并不能确保他们选择的值在我的样本中。

例如,假设我的样本是 4 5 6 6 2,使用我当前使用的代码,用户可以 select 任何值,例如 1、0,甚至 200,即使其中 none 个在给定的样本集中。如果我能解决这个问题,那么我要做的其余工作就会很简单。

如有任何支持,我们将不胜感激

大概是这样的:


#Rolls <- c( 4,5,6,6,2 )

set.seed(100)
Rolls<-sample(1:6, 5, replace=TRUE)
chosen <- c()
ordinals <- c("first","second")

while( length(chosen) < 2 ) {

    cat( "Dice = ",Rolls, "\n" )

    pick <- readline(
        prompt=paste("Please enter the", ordinals[length(chosen)+1],"value you'd like to add: ")
    )

    if( pick %in% Rolls ) {
        chosen <- append( chosen, as.numeric(pick) )
        Rolls <- Rolls[ -match( pick, Rolls ) ]
    } else {
        cat("Whoops, that's not a valid choice!\n")
    }

}

在我的会话中看起来像这样:


Dice =  2 6 3 1 2 
Please enter the first value you'd like to add: 4
Whoops, that's not a valid choice!
Dice =  2 6 3 1 2 
Please enter the first value you'd like to add: 2
Dice =  6 3 1 2 
Please enter the second value you'd like to add: 5
Whoops, that's not a valid choice!
Dice =  6 3 1 2 
Please enter the second value you'd like to add: 3

您需要自己控制该逻辑。试试这个功能:

readline_int <- function(..., lo = -Inf, hi = Inf, maxtries = 10) {
  ans <- as.numeric(readline(...))
  while (maxtries > 0 && (anyNA(ans) || ans < lo || ans > hi)) {
    warning("value not within expected bounds: [", lo, ",", hi, "]")
    maxtries <- maxtries - 1
    ans <- as.numeric(readline(...))
  }
  ans
}

readline_int(prompt="Please enter the first value you'd like to add: ", lo=1, hi=6)
# Please enter the first value you'd like to add: 9
# Warning in readline_int(prompt = "Please enter the first value you'd like to add: ",  :
#   value not within expected bounds: [1,6]
# Please enter the first value you'd like to add: 5
# [1] 5