I am new to R. I need to create a vector of length 37 with elements repeating the following pattern: 0.0, 0.0, 0.5, 0.5, 1.0, 1.0, 1.5, 1.5, ... , 2.5, 2.5, 3.0, 3.0, 2.5, 2.5, 2.0, 2.0, ..., 0.5, 0.5, 0.0, 0.0, 0.5, 0.5, ... The problem is, after creating the sequence, I do not know how to repeat it in the descending and increasing order alternately. Here is my code:
rep(seq(0.0,3.0,by = 0.5), each = 2, length = 37)
which only repeats the sequence in the general order. What should I supplement in my code to create a vector as required? Hope someone can help me solve this. Thank you so much!
CodePudding user response:
You can do something like this:
f <- function(length.out) {
b = c(0, rep(seq(0.5, 2.5, 0.5), each=2), 3.0)
n=ceiling(length.out-2)/10
c(0, rep(c(b, rev(b)),n), 0)[1:length.out]
}
Now, just call the function, passing your desired length:
f(37)
[1] 0.0 0.0 0.5 0.5 1.0 1.0 1.5 1.5 2.0 2.0 2.5 2.5 3.0 3.0 2.5 2.5 2.0 2.0 1.5 1.5 1.0 1.0 0.5 0.5 0.0 0.0 0.5 0.5 1.0
[30] 1.0 1.5 1.5 2.0 2.0 2.5 2.5 3.0
f(246)
[1] 0.0 0.0 0.5 0.5 1.0 1.0 1.5 1.5 2.0 2.0 2.5 2.5 3.0 3.0 2.5 2.5 2.0 2.0 1.5 1.5 1.0 1.0 0.5 0.5 0.0 0.0 0.5 0.5
[29] 1.0 1.0 1.5 1.5 2.0 2.0 2.5 2.5 3.0 3.0 2.5 2.5 2.0 2.0 1.5 1.5 1.0 1.0 0.5 0.5 0.0 0.0 0.5 0.5 1.0 1.0 1.5 1.5
[57] 2.0 2.0 2.5 2.5 3.0 3.0 2.5 2.5 2.0 2.0 1.5 1.5 1.0 1.0 0.5 0.5 0.0 0.0 0.5 0.5 1.0 1.0 1.5 1.5 2.0 2.0 2.5 2.5
[85] 3.0 3.0 2.5 2.5 2.0 2.0 1.5 1.5 1.0 1.0 0.5 0.5 0.0 0.0 0.5 0.5 1.0 1.0 1.5 1.5 2.0 2.0 2.5 2.5 3.0 3.0 2.5 2.5
[113] 2.0 2.0 1.5 1.5 1.0 1.0 0.5 0.5 0.0 0.0 0.5 0.5 1.0 1.0 1.5 1.5 2.0 2.0 2.5 2.5 3.0 3.0 2.5 2.5 2.0 2.0 1.5 1.5
[141] 1.0 1.0 0.5 0.5 0.0 0.0 0.5 0.5 1.0 1.0 1.5 1.5 2.0 2.0 2.5 2.5 3.0 3.0 2.5 2.5 2.0 2.0 1.5 1.5 1.0 1.0 0.5 0.5
[169] 0.0 0.0 0.5 0.5 1.0 1.0 1.5 1.5 2.0 2.0 2.5 2.5 3.0 3.0 2.5 2.5 2.0 2.0 1.5 1.5 1.0 1.0 0.5 0.5 0.0 0.0 0.5 0.5
[197] 1.0 1.0 1.5 1.5 2.0 2.0 2.5 2.5 3.0 3.0 2.5 2.5 2.0 2.0 1.5 1.5 1.0 1.0 0.5 0.5 0.0 0.0 0.5 0.5 1.0 1.0 1.5 1.5
[225] 2.0 2.0 2.5 2.5 3.0 3.0 2.5 2.5 2.0 2.0 1.5 1.5 1.0 1.0 0.5 0.5 0.0 0.0 0.5 0.5 1.0 1.0
Now, call the function
CodePudding user response:
I'm curious to see a better way than this:
a <- rep(seq(0.0,3.0,by = 0.5), each = 2, length = 14) # go up
b <- rev(a[3:12]) # go down, w/o ends
c <- c(a,b) # combine
rep(c, length.out = 37) # repeat for 37 elements
[1] 0.0 0.0 0.5 0.5 1.0 1.0 1.5 1.5 2.0
[10] 2.0 2.5 2.5 3.0 3.0 2.5 2.5 2.0 2.0
[19] 1.5 1.5 1.0 1.0 0.5 0.5 0.0 0.0 0.5
[28] 0.5 1.0 1.0 1.5 1.5 2.0 2.0 2.5 2.5
[37] 3.0
CodePudding user response:
Try this
rep(c(seq(0.0,3.0,by = 0.5),rep(seq(3.0,0.0,by = -0.5))), each = 2, length = 37)