0

I am a beginner at R and I'm trying to loop some binomial random samples to record a function of those random samples and then graph them.

I tried the following code. I know it's wrong but I don't know how to make it work.

for (i:10){
a = (rbinom(1,20,0.2))
b= 20 - a
c = (rbinom(1,50,0.3))
d = 50 - c
fi = a*b*c*d
i = i +1 
x <- list(fi)
}
Lunar
  • 13
  • 2
  • 1
    Hi, I suggest you provide an expected output (and try to make your question as specific as possible--at the moment it's pretty broad). [See this post for more info.](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) – heds1 Oct 07 '19 at 02:41

2 Answers2

0

Maybe you can try this:

x <- c()

for (i in 1:10){
  a <- rbinom(1,20,0.2)
  b <- 20 - a
  c <- rbinom(1,50,0.3)
  d <- 50 - c
  fi <- a*b*c*d
  x[i] <- fi
}
TheN
  • 523
  • 3
  • 7
0

You have the wrong format for the for command. You are incrementing the index variable, i, but the for command does that for you. You are overwriting the value of x on each pass through the loop so only the last one is returned. You really need to take advantage of some of the free tutorials on R that are readily available on the web. A better approach is not to use the for command at all. Create a function that does what you want and then run that function as many times as you want:

rsam <- function() {
     a <- rbinom(1, 20, 0.2)
     b <- 20 - a
     c <- rbinom(1, 50, 0.3)
     d <- 50 - c
     a*b*c*d
}
fi <- replicate(100, rsam())

Now fi contains the values of 100 trials of your function.

dcarlson
  • 10,936
  • 2
  • 15
  • 18