简体   繁体   English

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

[英]Accessing elements in a list of nested vectors

have the following list of vectors:有以下向量列表:

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

need to use a for loop to access the keys, values in the list so the output looks like this:需要使用 for 循环来访问列表中的键和值,因此 output 看起来像这样:

eric likes the tigers

tate likes the vols and titans

heather likes the gators and tide

our code can't "hard code" the number of elements in the list... so that if I add elements to one of the我们的代码不能“硬编码”列表中的元素数量......所以如果我将元素添加到其中一个

lists nested in the vectors it will still work.嵌套在向量中的列表仍然可以工作。 I'm pretty sure they want me to use a for loop.我很确定他们希望我使用 for 循环。

# 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 " ) ) )
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM