I have been trying to create a function for the sequence of following series:
1,-2,-3, 4, 5, 6, -7 ,-8, -9, -10........n (1 positive, 2 negatives, 3 positives, 4 negatives … and goes on up to n).
Creating a non-negative sequence is quite easy, but these negative terms are testing me.
If anyone can help me over this
The simplest way to create a sequence of numbers in R is by using the : operator. Type 1:20 to see how it works. That gave us every integer between (and including) 1 and 20 (an integer is a positive or negative counting number, including 0).
The function rep() in R will repeate a number or a sequence of numbers n times. For example, typing rep(5, 5) wiull print the number 5 five times.
Definition: The sign R function returns the signs of numeric elements. The value 1 is returned for positive numbers, the value 0 is returned for zero, and the value -1 is returned for negative numbers.
out equally spaced values from from to to . ( length. out is usually abbreviated to length or len , and seq_len is much faster.) The fourth form generates the integer sequence 1, 2, …, length(along. with) .
Here's a way to do this.
myfun <- function(n) {
myvec <- integer(n)
for (i in seq_len(n)) {
curtri <- ceiling(sqrt(i*2 + 0.25) - 0.5)
myvec[i] <- i * (-1)^(curtri + 1)
}
return(myvec)
}
myfun(10)
[1] 1 -2 -3 4 5 6 -7 -8 -9 -10
It takes advantage of the fact that you can find which triangular number you are at with sqrt(i*2 + 0.25) - 0.5
. By applying even to non triangular numbers, we can determine the index of the next triangular number, and use that as the exponent for -1
.
There's probably a better way, though.
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