0

I have a vector with values which I want to include in the first row of a matrix that will be filled in the two next for-loops, so it would be three for loops. I already tried cat and paste but without success.

So my problem is inserting the value of v1 with the name of matrix cart_, in a way the name would be cart_1 (when v1 is 1)

for (v1 in 1:5){
  cart_ <- matrix(0,n_mes,n_simu)
  cart_  < -capital_inicial[v1,1]
0

2 Answers 2

1

A good practice is to use a named list :

cart <- list()
for (v1 in 1:5){
  cart[[paste0("cart_", v1)]] <- matrix(0,3,3)
}

You can access cart_1 with :

cart[["cart_1"]]

Create n object cart_1 to cart_n is not a good practice. One object containing you n objects is better. If you have 2 consecutive loops of different size, an object that you don't want may remain.

Sign up to request clarification or add additional context in comments.

Comments

0

This is actually question 7.21 in the R FAQ (https://cran.r-project.org/doc/FAQ/R-FAQ.html#How-can-I-turn-a-string-into-a-variable_003f

The most important part of that answer is near the end where it points out that it is often easier to use a list. @Clemsang gave an example of using a list in a for loop.

Using a list instead of global variables makes it much less likely that you will accidentally overwrite another variable and make it much easier to work with your results. If you want to do something with each of your new matrices, then you can just reference them in a loop similar to how they were created instead of having to worry about get (or use lapply or sapply to make it even easier) and if you want to copy/save/delete/etc. all the matrices, you have a single object to work with instead of needing to loop again.

In your example above, the main result of the loop is to make several assignments. In this case it is often easier and better to use a lapply or a related function instead of the explicit loop. For example:

garage <- lapply( 1:5, function(v1) {
                        matrix( rnorm(v1^2, 10, 3), v1, v1)
                       } )
names(garage) <- sprintf("cart_%d", 1:5)
garage[["cart_3"]]
tmpvar <- "cart_5"
garage[[tmpvar]]

sapply(garage, det)

rm(garage)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.