Sapply in R how to use?

I am a C ++ programmer and I am new to R. Someone told me that using a for loop in R is a bad idea and it is better to use sapply . I wrote the following code to calculate the probability of a birthday match :

 prob <- 1 # prob of no coincidence days <- 365 k <- 50 # how many people probability <- numeric() #probability vector (empty right now) for(i in 1:k){ prob <- (days - i + 1)/days * prob # Formula for no coincidence probability[i] <- 1 - prob } 

How can I do the same with sapply ? I want to do something like:

 1 - sapply(1:length(m), function(x) prod(m[1:x])) 

But how to use a formula to match a birthday?

+4
source share
2 answers

You can do:

 m <- (days - seq_len(k) + 1) / days probability <- 1 - sapply(seq_along(m), function(x) prod(m[1:x])) 

but this will be absent in the useful cumprod function:

 probability <- 1 - cumprod(m) 

which will be much faster.

(Also gave you a peak in seq_along and seq_len , which is more stable than : when working with vectors of zero length.)

+6
source

For a specific question, it is probably best to use the built-in birthday probability calculator

 sapply(1:50, pbirthday) 
+4
source

Source: https://habr.com/ru/post/1497709/


All Articles