Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding seq_len in R

Tags:

r

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.

like image 838
Tony Avatar asked Oct 23 '25 07:10

Tony


1 Answers

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"
> 

Also 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.

like image 166
U12-Forward Avatar answered Oct 24 '25 21:10

U12-Forward



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!