write a simple loop in R

I have the following R code to generate 100 random weights

# Creating a matrix to store the weights
all_wts <- matrix(nrow = 100,
ncol = length(tickers))1 = 100  ### number of tickers 4 `                  
# run the for loop 100 times.
for (i in 1:np1) {
wts <- runif(length(tickers))
wts <- wts/sum(wts)`
# Storing weight in the matrix
all_wts[i,] <- wts }

So I should have a matrix of weights
$$ w= \begin{bmatrix}
w_1 & w_2 & w_3 & w_4 \
\vdots& \vdots & \vdots & \vdots \
\vdots & \vdots & \vdots & \vdots \
\end{bmatrix}$$

where first row
$$ w^* = \begin{bmatrix}w1 & w2 &w3& w4 \end{bmatrix} $$ is the first set of random weights etc .

Now my second step is to multiply first set of random weights with another matrix called $$R_t $$ where $$R_t = \begin{bmatrix}
A_1 & A_2 &A_3 & A_4 \
\vdots& \vdots & \vdots & \vdots \
A_{1,252} & A_{2,252} & A_{3,252}& A_{4,252} \
\end{bmatrix}$$

a1<- all_wts[1,] 
b<-return
yts <-  rowSums(a1*b) 

Then I repeat this multiplication with the second random weights such as

a2<- all_wts[2,] 
b<-return
yts2 <-  rowSums(a2*b) 

I do this for all 100 random weights. My question is, how can I write one code to implement all multiplications for each random weights in and store the results of step 2 for each random weights in a new matrix so I can move to the third step which needs the results of step 2.

Any ideas will be appreciated.

Hi,

In order for us to help you with your question, please provide us a minimal reproducible example where you provide a minimal (dummy) dataset and code that can recreate the issue. Once we have that, we can go from there. For help on creating a Reprex, see this guide:

Good luck!
PJ

What is this supposed to do? Perhaps you want something like this?

all_wts <- matrix(rep(NA, 100), nrow = 100,  ncol = 1) 

Both tickers and np1 are undefined.

tickers = 4 , np1 =100 .

My question is how to simplify my code for the following iteration
a1<- all_wts[1,]
b<-return
yts <- rowSums(a1*b) , do this calculation for 100 times

e.g a2<- all_wts[2,]
b<-return
yts <- rowSums(a2*b)

As As pieterjanvc says we need a MWE.

This loop is not doing what I think you expect. It is generating a random number then dividing that number by itself ast storing the result in the matrix all_wts.

tickers <- 4; np1 <- 100
all_wts <- matrix(nrow = 100, ncol = 1)   

# run the for loop 100 times.
for (i in 1:np1) {
  wts <- runif(length(tickers))
  wts <- wts/sum(wts)
  # Storing weight in the matrix
  all_wts[i,1] <- wts 
}
head(all_wts)
#>      [,1]
#> [1,]    1
#> [2,]    1
#> [3,]    1
#> [4,]    1
#> [5,]    1
#> [6,]    1

Created on 2023-01-17 with reprex v2.0.2