How to change the value of x_i vectors?

Viewed 41

Hi everyone I'm working with 200 vectors like this:

x_1 
x_2
x_3
.
.
x_200

So I wanted to make a for loop to change the value of each vector like this

for (i in 1:200){
   x_i <- runif(1000,min = 0, max = 1)
}

But I don't know how to make r realize that I want to modify the i of the xi vector in each iteration.

2 Answers

Use assign

for (i in 1:200){
  assign(paste0("x_", i), runif(1000,min = 0, max = 1))
}

You could try storing them in a list to make it a bit neater. This is generally preferred to having lots of names of things in your global environment.

n = 200
vector_list = lapply(1:n, function(x) runif(1000, min = 0, max = 1))
names(vector_list) = paste0("x_", 1:n)

Then access an element like:

> vector_list["x_3"]
$x_3
  [1] 0.293589555 0.878310051 0.149773513 0.888951762 0.413800260 0.239410186
  [7] 0.318712166 0.409540908 0.107566600 0.578909791 0.337214331 0.893359107
...

and perform a function to them

sapply(vector_list, mean)
   x_1       x_2       x_3       x_4       x_5       x_6       x_7       x_8 
0.4926471 0.4829152 0.4916485 0.4847532 0.5015119 0.4862118 0.5048847 0.4946440 
      x_9      x_10      x_11      x_12      x_13      x_14      x_15      x_16 
0.5161292 0.4966456 0.4840273 0.4993027 0.4994515 0.4963940 0.5087290 0.4906113 
     x_17      x_18      x_19      x_20      x_21      x_22      x_23      x_24 
0.5100324 0.5095015 0.5058597 0.5093545 0.5130095 0.4902518 0.5152354 0.4963284 
...
Related