没有循环的解决方案可能是:
condition = which(Rolls==6)
if(length(condition)>=3){
Rolls[condition[3:length(condition)]] = sample(1:5, length(condition)-2, replace=TRUE)
}
Run Code Online (Sandbox Code Playgroud)
condition用 6 表示 Rolls 中的位置,如果超过 2,则选择第三个Rolls[condition[3:length(condition)]]并重新采样。
第二个问题可能是这样的:
remove = 3
Rolls = Rolls[-which(Rolls==remove)[1]]
Run Code Online (Sandbox Code Playgroud)
如果您愿意,您可以轻松地将它们放入函数中
编辑 1
为了使第二个答案更具交互性,您可以为其构建一个函数:
remove.roll = function(remove, rolls){
rolls = rolls[-which(rolls==remove)[1]]}
Run Code Online (Sandbox Code Playgroud)
然后用户可以remove随心所欲地调用该函数。您还可以制作一个从提示中获取信息的程序:
remove = readline(prompt="Enter number to remove: ")
print(Rolls = Rolls[-which(Rolls==remove)[1]])
Run Code Online (Sandbox Code Playgroud)