首页 > 解决方案 > 访问嵌套向量列表中的元素

问题描述

有以下向量列表:

ourTeams <- list("eric" = c("tigers"), "tate" = c("vols","titans"),"heather" = c("gators","tide"))

需要使用 for 循环来访问列表中的键、值,因此输出如下所示:

eric likes the tigers

tate likes the vols and titans

heather likes the gators and tide

我们的代码不能“硬编码”列表中的元素数量......所以如果我将元素添加到其中一个

嵌套在向量中的列表仍然可以工作。我很确定他们希望我使用 for 循环。

标签: r

解决方案


# list example
ourTeams <- list("eric" = c("tigers"), "tate" = c("vols", "titans"), "heather" = c("gators","tide"))

# list indexing
ourTeams[1]
names(ourTeams[1])
ourTeams[[1]]

# paste0 with sep and collapse
paste0( ourTeams[[2]], sep="," ) # vector of string
paste0( ourTeams[[2]], collapse=", " ) # collapse to a single string

# sprintf (%s for string)
sprintf("my stackoverflow reputation is %s", "10")

# putting this together
for(i in 1:3) {
  print( sprintf("%s likes the %s", names(ourTeams[i]), paste0(ourTeams[[i]], collapse=" and " ) ) )
}

推荐阅读