Zerbraxi
Zerbraxi

Reputation: 123

Find Index of Specific Value in R

I am currently working on a homework problem and have come across an issue. The problem I am working on is a modified version of the classic Birthday problem. However I am also trying to now not just figure out the probability that two people have the same birthday but more specifically the probability that someone else has the exact same birthday as myself.

Below is the working functions for the existing birthday problem for the assignment.

birthdays = function(n) {
s = sample(1:365, n, replace = TRUE)  
return(s)
}

duplicate.birthdays = function(n) {
b = birthdays(n)
dups = anyDuplicated(b)
dups = any(dups>0)
return(dups)
}

prob.duplicate =function(n) {
r = replicate(5000, duplicate.birthdays(n))
prob = sum(r) / length(r)  
return(prob)
}

n = 1:100     # number of people I'm sampling from
probs = sapply(n, prob.duplicate)

I have attempted to modify these functions in order to specifically target if someone has the same birthday as myself. I have assumed that out of 1 - 365 days I am looking for any time the number 1 appears again as I am assuming 1, or January 1st is my birthday.

Below is my modified version of the duplicate.birthdays function

duplicate.birthdays = function(n) {
b = birthdays(n)
index = 1:length(b)
x = 1
index.get.1 = index [x=1]
return(index.get.1)
}

However I am always getting returned the first index instead of whether or not an index matches the value 1.

Any help would be greatly appreciated and hopefully this is enough information to understand essentially what I am trying to get at.

Upvotes: 1

Views: 2115

Answers (1)

jeremycg
jeremycg

Reputation: 24945

Your function is a little weird: You are subsetting by x=1 which is always going to be 1.

Try something like:

duplicate.birthdays <- function(n) {
    which(birthdays(n)==1)
}

Upvotes: 2

Related Questions