Pierre PM Martin
Pierre PM Martin

Reputation: 11

A loop to create a list

I would like to form a list thanks to a loop.

I have a list of variables called:

var1, var2, ... varN

And I would like to create easily a list of length named listvar with:

unlist(listvar[i])=vari   (with i in 1:N)

Is someone inspired ?

Upvotes: 0

Views: 90

Answers (1)

Konrad Rudolph
Konrad Rudolph

Reputation: 546073

The code makes me wonder why the variables var1 … varN exist in the first place: they shouldn’t. Instead, generate the list directly.

That said, you can easily retrieve the value of a variable given by its name using get. This doesn’t even require a loop, you can use R’s vectorised operations.

varnames = paste0('var', 1 : N)
listvar = mget(varnames)

Upvotes: 2

Related Questions