访问嵌套向量列表中的元素

问题描述 投票:0回答:1

具有以下向量列表:

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循环。

具有以下向量列表:ourTeams

r
1个回答
0
投票
# 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 " ) ) )
}
© www.soinside.com 2019 - 2024. All rights reserved.