 # error message 1:N

Please can someone help, when I am running this code. I am getting an error message which says
Error in 1:N : NA/NaN argument
In 1:N : numerical expression has 5 elements: only the first used

``````birthday_part02 = function(N) {
# Initialise counter
count = 0
# Loop by the number of iteration defined by the value N
for (i in 1:N) {
# Generate a sample of birthdays
birthdays = sample(1:365, 10, replace = T)
if (length(unique(birthdays)) < 10) {
# If there duplicate birthday increase counter
count = count + 1
}
}
return(count / N)
# Return the proporation of duplicates
}

# Assign a vector of those numbers to N
N = c(10, 50, 100, 1000, 10000)

# A for loop that loops for a length of 5
prop_people = numeric(length = 5)
for (i in 1:N) {
prop_people[i] = birthday_part02(N[i])
}
``````

It looks like you probably want `for (i in 1:length(N))` or `for (i in seq_along(N))`.

The current version of your code is using the first element of `N` to define the loop variable range and is therefore equivalent to `for (i in 1:10)`. When `i` equals 6, it throws an error, since `N` equals `NA`. For example, try running the following:

``````birthday_part02(N)
birthday_part02(NA)
``````
1 Like

Thanks very much for your help using the length(N) has fixed the issue. Thanks a lot.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.