如何解决如何获取用户从样本中选择的值?
我有一个由“Rolls
我想要做的是让用户从样本中选择两个值,然后我希望将这两个值添加并存储在样本中。 (我不需要对加法中使用的值发生任何事情)
我的主要问题是我一直在使用:
"first_number
这并不能确保他们选择的值在我拥有的样本内。
例如,假设我的样本是 4 5 6 6 2,使用我当前使用的代码,用户可以选择任何值,例如 1、0 甚至 200,即使这些都不是在给定的样本集中。如果我能解决这个问题,那么我接下来要做的事情就会很简单。
非常感谢任何支持
解决方法
可能是这样的:
#Rolls <- c( 4,5,6,2 )
set.seed(100)
Rolls<-sample(1:6,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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。