lundi 2 mai 2016

R: ReEvaluating a function in every row of a table

I want to simulate drawing 10 balls out of a bag of 20 with a 50/50 colour distribution of black and white. After drawn, the balls should not be put back. The value i am intereseted in is the amount of whites which were drawn each time.

For that purpose i created a function, which gives me that exat value. It first creates a list of random numbers from 1 to 20 (sample), then sorts out the blacks (Numbers of 11 or higher) and after that gives me the amount of remaining numbers ( length(whites) )

wins <- function()
{
sample <- sample(1:20, 10, replace = FALSE)
whites <- subset(sample, sample<= 10)
return(length(whites))
}

Now i want to create a table of 500 entries, which each being a value given by the function. When i put it in a data.table it will just evaluate the function once and give me a table with 500 identical entries.

data.table(shot=c(1:500), k=wins())

     shot k
  1:    1 5
  2:    2 5
  3:    3 5
  4:    4 5
  5:    5 5
  ---       
496:  496 5
497:  497 5
498:  498 5
499:  499 5
500:  500 5

What do i have to do differently?




Aucun commentaire:

Enregistrer un commentaire