Reputation: 429
I am aiming to produce a sequence something like this:
> c(1, rep(9, 7))
[1] 1 9 9 9 9 9 9 9
> c(9, 1, rep(9, 6))
[1] 9 1 9 9 9 9 9 9
> c(rep(9, 2), 1, rep(9, 5))
[1] 9 9 1 9 9 9 9 9
In essence, I have a sequence that stays constant, but I want to move a value along, one space at a time.
Obviously I could write this out in a way similar to what I have done, but my real sequence is much larger so this isn't that practical. My search for this has been somewhat futile so any advice would be appreciated. Thanks
Upvotes: 2
Views: 72
Reputation: 23101
Yet another way to get the same result:
x <- c(1, rep(9, 7))
sapply(8:1, function(n)c(tail(x,-n),head(x,n)))
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,] 1 9 9 9 9 9 9 9
[2,] 9 1 9 9 9 9 9 9
[3,] 9 9 1 9 9 9 9 9
[4,] 9 9 9 1 9 9 9 9
[5,] 9 9 9 9 1 9 9 9
[6,] 9 9 9 9 9 1 9 9
[7,] 9 9 9 9 9 9 1 9
[8,] 9 9 9 9 9 9 9 1
Upvotes: 1
Reputation: 51582
You can create a matrix and replace the diagonal, i.e.
m1 <-matrix(data = 9, nrow = 8, ncol = 8)
diag(m1) <- 1
m1
# [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
#[1,] 1 9 9 9 9 9 9 9
#[2,] 9 1 9 9 9 9 9 9
#[3,] 9 9 1 9 9 9 9 9
#[4,] 9 9 9 1 9 9 9 9
#[5,] 9 9 9 9 1 9 9 9
#[6,] 9 9 9 9 9 1 9 9
#[7,] 9 9 9 9 9 9 1 9
#[8,] 9 9 9 9 9 9 9 1
A one liner for that would be:
`diag<-`(matrix(data = 9, nrow = 8, ncol = 8),1)
Upvotes: 4
Reputation: 132576
You can use stats::filter
:
x <- c(1, rep(9, 7))
for (i in 1:8) print(x <- c(filter(x, c(0, 1), circular = TRUE, sides = 1)))
#[1] 9 1 9 9 9 9 9 9
#[1] 9 9 1 9 9 9 9 9
#[1] 9 9 9 1 9 9 9 9
#[1] 9 9 9 9 1 9 9 9
#[1] 9 9 9 9 9 1 9 9
#[1] 9 9 9 9 9 9 1 9
#[1] 9 9 9 9 9 9 9 1
#[1] 1 9 9 9 9 9 9 9
Obviously, this moves all values along and might not be what you are looking for if you have more than two different values in the sequence. Your question is a bit unclear.
Upvotes: 2
Reputation: 886938
An option is embed
embed(c(rev(v1),rev(v1)), length(v1))
# [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
#[1,] 1 9 9 9 9 9 9 9
#[2,] 9 1 9 9 9 9 9 9
#[3,] 9 9 1 9 9 9 9 9
#[4,] 9 9 9 1 9 9 9 9
#[5,] 9 9 9 9 1 9 9 9
#[6,] 9 9 9 9 9 1 9 9
#[7,] 9 9 9 9 9 9 1 9
#[8,] 9 9 9 9 9 9 9 1
#[9,] 1 9 9 9 9 9 9 9
embed(c(rev(v2),rev(v2)), length(v2))
# [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
# [1,] 1 5 5 5 3 2 5 7
# [2,] 7 1 5 5 5 3 2 5
# [3,] 5 7 1 5 5 5 3 2
# [4,] 2 5 7 1 5 5 5 3
# [5,] 3 2 5 7 1 5 5 5
# [6,] 5 3 2 5 7 1 5 5
# [7,] 5 5 3 2 5 7 1 5
# [8,] 5 5 5 3 2 5 7 1
# [9,] 1 5 5 5 3 2 5 7
v1 <- c(1, 9, 9, 9, 9, 9, 9, 9)
v2 <- c(1, 5, 5, 5, 3, 2, 5, 7)
Upvotes: 1