Im new to coding and using r and have 2 questions about seq_len(n).
My first question is that in one of my lecture notes we were told to use seq_len(n) instead of 1:n because it helps in the situation for n=0. When creating a loop to calculate the factorial using seq_len(n) instead of 1:n resulted in n=0 being 1 for 0! I don't understand why this works.
For my second question, I created a function for double factorial and in my equation I used the formula prod(2*seq_len(n/2)) and I noticed that regardless of what the integer beside seq_len(0) is the prod() function gives an output of 1 which does not make sense to me since seq_len(0) gives a numeric(0) and any number multiplied by 0 should be zero.
If n = 0, 1:n would give:
> 1:0
[1] 1 0
>
It gives ranges, but if n2 is smaller than n1, it get's treated as vector definitions, like:
> as.integer(c(1, 0))
[1] 1 0
>
Which isn't what we want, whereas seq_len gives:
> seq_len(0)
integer(0)
>
You might be wondering why is it an integer, but even for seq_len where n > 0, it is a class of integer:
> class(seq_len(0))
[1] "integer"
> class(seq_len(100))
[1] "integer"
>
integer(0) isn't 0, it specified that the integer vector has 0 elements!!!As in RStudio documentation:
The
seq_len(number)function creates a sequence that starts at 1 and with steps of 1 finishes at the number value. A common use of this function is to create indexes that match the length of a vector in order to make plots.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With