Automate number creation in a loop in R

Asked

Viewed 97 times

3

The figures after ^ (1, 2 and 3) are the values I wish to automate (increasing: 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 loop for:

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

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

  • 2

    It’s not just replacing 1.15^1 for 1.15^i?

2 answers

3

An answer was given by @Marcus Nunes in the comment box. The expression is then:

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

3


When you have several similar objects, the general rule is to have them in a list. Instead of having n (in this case 10) objects in the .GlobalEnv you only get one.
To create this list no cycle is required for, 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 of, as they all have the same length, we can transform them into column vectors of a matrix,

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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.