Galactus
Galactus

Reputation: 53

Creating vectors with different names in for loop using R

I want to create vectors having a different character name in a loop but without indexing them to a number as it is shown in this post. The names I want for the vectors are already in a vector I created.

Id <- c("Name1","Name2")

My current code creates a list

ListEx<- vector("list", length(Id))

## add names to list entries

names(ListEx) <- Id

## We run the loop 

for (i in 1:length(Id)){
  ListEx[[i]]<-getbb(Id[i])  
}
##The getbb function returns a 2x2 matrix with the maximum 
#and the minimum of the latitute/longitude of the city (which name is "Namei")


## Check the values of a matrix inside the list
ListEx[["Name1"]]  

I woud like to have Name1 as a vector containing the values of ListEx[["Name1"]]

Upvotes: 1

Views: 751

Answers (1)

SamR
SamR

Reputation: 20445

You are just missing one line of code. I have created a dummy function that creates a 2x2 matrix here:

Id <- c("Name1","Name2")

ListEx<- vector("list", length(Id))

## add names to list entries

names(ListEx) <- Id

f <- function(v) { return(matrix(rnorm(4), nrow=2))}

## We run the loop 

for (i in 1:length(Id)){
  ListEx[[i]]<-f(Id[i])  
}

## Check the values of a matrix inside the list
ListEx[["Name1"]]  

list2env(ListEx, globalenv()) # This is the relevant line

Name1
#            [,1]      [,2]
# [1,] -0.4462014 0.3178423
# [2,]  1.8384113 0.7546780
Name2
#            [,1]      [,2]
# [1,] -1.3315121 2.1159171
# [2,]  0.2517896 0.1966196

Upvotes: 1

Related Questions