Sunday, 18 August 2013

sapply in R, how to use?

sapply in R, how to use?

I am a C++ programmer and I am new in R. Someone tell me that using for
loop in R is a bad idea... That is better to use sapply. I have the
following code to calculate the probability of birthday coincidence:
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 I can do the same thing with the sapply?? I want to do something like:
1-sapply(1:length(m), function(x) prod(m[1:x]))
But how to use the formula for no coincidence of birthday??
Thanks!!

No comments:

Post a Comment