Automate the creation of numbers in a loop in R

3

The digits after ^ ( 1 , 2 and 3 ) are the values that I want to automate (incrementally: from 1 to ith value):

var1<-rnorm(3,5000,1300)/1.15^1
var2<-rnorm(3,5000,1300)/1.15^2
var3<-rnorm(3,5000,1300)/1.15^3

But, automate within a for loop:

for(i in 1:10){
name<-paste0('var',i)
assign(name,rnorm(3,5000,1300)/1.15^1)
}

How to insert this automation in the for loop and avoid writing one function at a time?

    
asked by anonymous 20.08.2018 / 05:28

2 answers

3

When you have several similar objects, the general rule is to have them in list . Instead of having n (in this case 10) objects in .GlobalEnv you only have one. To create this list you do not need a for loop, it can be done with lapply .

var_list <- lapply(1:10, function(i) rnorm(10, 5000, 1300)/1.15^i)
names(var_list) <- paste0("var", 1:10)
var_list

This has the advantage that, since they are all the same length, we can transform them into column vectors of an array,

mat_var <- do.call(cbind, var_list)
mat_var

or a data.frame .

df_var <- do.call(cbind.data.frame, var_list)
df_var

Then you can use the R functions that operate on tables.

    
20.08.2018 / 14:15
3

A response was given by @Marcus Nunes in the comment field. The expression is then:

for(i in 1:10){
    name <- paste0('var', i)
    assign(name, rnorm(3, 5000, 1300)/1.15^i)
}
    
20.08.2018 / 13:58