Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a Sequence with positive and negative numbers in R

Tags:

r

sequence

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

like image 759
1089 Avatar asked Sep 03 '14 16:09

1089


People also ask

How do you make a sequence of numbers in R?

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

How do I print a sequence in R?

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.

How do you know if a number is positive or negative in R?

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.

What does length out mean in R?

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


1 Answers

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.

like image 75
Will Beason Avatar answered Sep 30 '22 01:09

Will Beason