Home > Mobile >  how can I use if condition inside the loop in r
how can I use if condition inside the loop in r

Time:04-28

I defined a function creates 3 random numbers from 1 to 36, and I allowed repetition. I want to test how many times I can get three same numbers in one hand in 1000 iterations using if statement inside the loop. I don't know what's happening there:

f <- function(all){
  all <- seq(1:36)
  hand <- sample(all, 3, replace=T)
  return(c((hand),(sum(hand))))
}
f()
hand <- f()
hand


a=NaN

for (i in 1:1000){
  hand[i] <- f()
  if (hand[1]=hand[2]=hand[3]){
    a[i]=TRUE
  }else{
    a[i]=FALSE
  table(a)["TRUE"]
  }
}

CodePudding user response:

Alternative approach:

set.seed(99)

hands <- replicate(1000, sample(seq(1:36), 3, replace = TRUE))

table(apply(hands, 2, function(x) any(duplicated(x))))
FALSE  TRUE 
  902    98 

which is identical to:

set.seed(99)
a <- c()

for (i in 1:1000){
  hand <- f()
  if(any(duplicated(hand))){
    a[i] <- TRUE
  } else{
    a[i] <- FALSE
  }
}
table(a)
FALSE  TRUE 
  902    98

CodePudding user response:

I think the issue is how you are saving your results. See comments below:

f <- function(all){
  all <- seq(1:36)
  hand <- sample(all, 3, replace=T)
  return(c((hand),(sum(hand))))
}
f()
hand <- f()
hand


##a=NaN
a <- vector(mode = "numeric",length = 10000)
for (i in 1:10000){
  # change from   hand[i] <- f()
  # to hand <- f(), basically hand is a vector of length 3, you are trying to save an element of length 4 into the first value of length 1
  hand <- f()
  # Need to use = not == and do multiple comparisons (hand-[1
  if ((hand[1]== hand[2]) & (hand[2]== hand[3])){
    a[i]=TRUE
  } else{
    a[i]=FALSE
    # table(a)["TRUE"]
    # not sure what yyou want to do 
  }
}

CodePudding user response:

More generally, we can build a function to see how many repetitions we'll have with a sample size n, minimum value min, maximum value max, repeated times times.

f <- function(n, min, max, times){
  all <- floor(runif(n, min, max))
  hand <- as.data.frame(NA)
  for (i in 1:times){
  hand[i, 1:n] <- floor(runif(n, min, max))}
}

You can try with three values in each sample, minimum 1, maximum 36, and repeated 1000 times: hand <- f(3, 1, 36, 1000)

Then you can check how many repetitions there are (regardless of the order of the three values):

n_repetitions= duplicated(t(apply(hand, 1, sort)))
sum(n_repetitions)
  • Related