3

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"]]

Galactus
  • 71
  • 5
  • You have an undefined function in your loop, `ListEx[[i]]<-f(Id[i])`. What does `f()` do? In any case, you are running `f("Name1")` - so it doesn't look like a function which creates a matrix... – SamR Jun 29 '22 at 11:08
  • The ```f``` function is ```getbb()``` from the osm package. It fetches geographic coordinates of the city name in the function by going on the OpenStreetMap website. It returns a 2x2 matrix with the maximum and the minimum of the latitute/longitude of the city. – Galactus Jun 29 '22 at 11:35

1 Answers1

1

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
SamR
  • 8,826
  • 3
  • 11
  • 33
  • Thanks it does extract all the elements of the list ! Now they are 2x2 matrices and I want them to be row vectors, how can I change it? Wouldn't it be easier to do it to create the row vectors inside the loop? – Galactus Jun 29 '22 at 12:03
  • 1
    Yes probably easier to do `ListEx[[i]]<-as.vector( f(Id[i]) )` in the loop. – SamR Jun 29 '22 at 12:04