Hello,

Question 1: I’m trying to repeat a row_vector n times using:

```
model {
//...
row_vector[2] myvector = [1,2];
row_vector[6] myvector2;
myvector2 = rep_row_vector(myvector, 3)
//...
}
```

I get:

No matches for:

rep_row_vector(row vector, int)

Available argument signatures for rep_row_vector:

rep_row_vector(real, int)

Question 2: I suppose the above performs the equivalent in R to `rep(c(1,2),times = 3)`

. How about `rep(c(1,2), each = 3)`

in Stan?

Thanks in advance.

There isn’t a `rep_`

function to copy a (row) vector into a longer (row) vector. You could do something like

```
row_vector[6] = append_col(append_col(my_vector, my_vector), my_vector);
```

1 Like

Thank you @bgoodri for your quick answer. Any alternative to repeat each element of vector n times as in R `rep(my_vector, each = n)`

?

You would have to just do a loop.

1 Like

@bgoodri what would such a loop look like (in this case) ?

Here’s one approach. The defined function can then be used in any other block.

(Please note: There may very well be more efficient ways of doing this - I’m not a programmer by training or trade - as should be evident from the number of edits…).

```
functions{
vector repeat_vector(vector input, int reps){
int index[rows(input) * reps];
for (i in 1:reps){
for (j in 1:rows(input)){
index[j + rows(input) * (i-1)] = j;
}
}
return(input[index]);
}
}
```

Edit: Doh, saw now that you wanted the rep() function with the “each” argument. Then you have to switch the construction of the index vector around, like this:

```
functions{
vector repeat_vector(vector input, int reps){
int index[rows(input) * reps];
for (i in 1:rows(input){
for (j in 1:reps){
index[j + rows(input) * (i-1)] = i;
}
}
return(input[index]);
}
}
```

2 Likes

Thank you @erognli, I could work around the rep(x, each = n) function, by defining an index in R. But this may be helpfull in the future!

Here’s code for repeating a vector K times, and an N*M matrix K times:

```
functions {
vector repeat_vector(vector input, int K) {
int N = rows(input);
vector[N*K] repvec; // stack N-vector K times
for (k in 1:K) {
for (i in 1:N) {
repvec[i+(k-1)*N] = input[i]; // assign i-th value of input to i+(k-1)*N -th value of repvec
}
}
return repvec;
}
matrix repeat_matrix(matrix input, int K) {
int N = rows(input);
int M = cols(input);
matrix[N*K,M] repmat; // stack N*M matrix K times
for (k in 1:K) {
for (i in 1:N) {
repmat[i+(k-1)*N] = input[i]; // assign i-th row of input to i+(k-1)*N -th row of repmat
}
}
return repmat;
}
}
```

1 Like