Home > Mobile >  How to create a sequence of numbers in R from min to max with zero as the midpoint?
How to create a sequence of numbers in R from min to max with zero as the midpoint?

Time:06-30

If I had the following variable.

set.seed(20)
variable <- sample(-74:124.2, size = 38)

How can I create a sequence of 5 numbers using the min and max values of variable and zero as the midpoint (3rd value)?

seq() takes the start and end values, but is there a way to do this by specifying a middle value?

seq(min(variable), max(variable), length.out = 5)

CodePudding user response:

You can replace the median of the generated sequence with a specified value:

seq(min(variable), max(variable), length.out = 5) -> x        
x[which(x == median(x))] <- 0

#-73.00 -25.75   0.00  68.75 116.00

This would work if the length(x) is odd.

CodePudding user response:

You can combine two seq.

c(seq(min(variable), 0, length.out=3), 
  seq(0, max(variable), length.out=3)[-1])
#[1] -73.0 -36.5   0.0  58.0 116.0

This will only work as expected when min(variable) <= 0 and max(variable) >= 0.

  •  Tags:  
  • r
  • Related