How to name an element in a loop?

Viewed 273

I am making a list of 76 components means, ranging from 0 to 0.75. I would like to know how to name the component dynamically. For example, I'd like to name the component lis_0,lis_0.01,lis_0.02 and so on. Also, instead of making a list with 76 components, how could I make each component an individual matrix?

thank you :)

I've tried the online sources.

x <- seq(0,0.75,0.01)
lis <-list()
for ( i in x) {lis<-matrix(rnorm(1000,mean = i,sd=1))}

I'd like to name the component lis_0,lis_0.01,lis_0.02 and so on.

2 Answers

It doesn't matter what std is, here is how you can specify the name. The key is to use the names function and use paste0 to create the name.

Here I also introduced you the lapply function, which is a nice alternative to for-loop.

set.seed(1)

x <- seq(0,0.75,0.01)

lst <- lapply(x, function(x) matrix(rnorm(1000, mean = x, sd = 1)))

names(lst) <- paste0("lis_", x)

I think you may have some issues in your code. For example, std is not defined and you are creating a list and then assigning a matrix.

Nevertheless, I think the core of your problem create a new object during each iteration and name it properly. This can be achieved using the assign() function.

Here is an example.

x <- seq(0,0.75,0.01)

for ( i in x) {
  lis <- matrix(rnorm(1000, mean = i, sd = sd(x)))
  name <- paste("lis",i, sep = "_")
  assign(name, lis)
}

I think you can start working from it.

Related