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])
}
## 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"]]
CodePudding user response:
You can consider something like :
Id <- c("Name1","Name2")
ListEx<- vector("list", length(Id))
names(ListEx) <- Id
for (i in 1:length(Id)){
ListEx[[Id[i]]]<-f(Id[i])
}
ListEx[["Name1"]]
CodePudding user response:
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