Ani
Ani

Reputation: 3

How to create a list of variables using a for loop in R

I have a list of 100 variables lets say v1 to v100. I want to create a list that holds each of these variable in a seprate column. What i have done is

s=list()
for (i in 1:100){
  name=paste("v",i,sep="")
  s[name]=vi

}

Now the problem is how to make R treat vi as name for the variable that will be stored in list. On running the above written code the console is showing the error

Error in s[name] = vi : 
`cannot coerce type 'closure' to vector of type 'list'

Upvotes: 0

Views: 2368

Answers (3)

WoDoSc
WoDoSc

Reputation: 2618

If you have your variables v1, v2, v3, etc. you can use:

s=list()
for (i in 1:100){
  name=paste("v",i,sep="")
  s[[name]]=get(name) #write to the list with [[ ]] operator
}

The get function returns the value of the variable with the name equal to the string passed as argument (if the variable exists).

Please note that this will copy the value, and it does not create a reference to that variables, as usual in R. So if you then change the value of a variable it does not also change in the list (and viceversa).

Upvotes: 0

Sven Hohenstein
Sven Hohenstein

Reputation: 81753

You can use mget to create a list based on multiple objects.

Here's an example:

v1 <- 1:3
v2 <- 4:6

mget(paste0("v", 1:2))
# $v1
# [1] 1 2 3
# 
# $v2
# [1] 4 5 6

The correct names are assigned automatically.

Upvotes: 3

Matt Bannert
Matt Bannert

Reputation: 28274

Ok, let's try to make things reproducible first.

# I generate a list of 100 random normal vector with 50 elements
s <- list()
for(i in 1:100) s[[i]] <- rnorm(50)

# Creating the names vector(!) does not need any loops. 
nms <- paste("v",1:100,sep="")

# if you already have the list like you say, you're done.
names(s) <- nms

Upvotes: 1

Related Questions