我想在循环中创建具有不同字符名称的矢量,但不将它们索引为数字,如本文所示。我想要的向量名已经在我创建的向量中了。
Id <- c("Name1","Name2")
我当前的代码创建了一个列表
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"]]
我想有Name1作为一个向量包含ListEx的值[["Name1"]]
您只缺少一行代码。我创建了一个虚拟函数,它在这里创建了一个2x2矩阵:
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