我有一个包含命名元素的列表,如下所示:
lst <- list(a1 = 5:12, b4 = c(34,12,5), c3 = 23:45)
我可以很容易地检索元素名称,如下所示:
names(lst)
在函数中,我可以在列表元素上循环,但如何访问循环中正在访问的元素的名称:
test <- function(lst) {
for (l in lst) {
cat("The name of the current list element is", ???, "n")
# Other processing of the list element
}
}
也许这可以帮助
for (l in seq_along(lst)) {
cat("The name of the current list element is", names(lst[l]), "n")
# Other processing of the list element
}
它给出
The name of the current list element is a1
The name of the current list element is b4
The name of the current list element is c3
在purrr
包中,有函数imap()
和iwalk()
。它们接受一个列表和一个带有两个参数的函数,并将该函数应用于列表的每个元素及其索引/名称。不同的是,iwalk
静默地返回NULL
,并且仅针对副作用执行(如果映射到cat()
,则会有所帮助(,而imap()
的工作原理与lapply()
类似,只是它使用了函数作为列表名称的第二个参数。
library(purrr)
lst <- list(a1 = 5:12, b4 = c(34,12,5), c3 = 23:45)
imap(lst,(x,y) cat("The name of the current list element is", y, "n"))
#> The name of the current list element is a1
#> The name of the current list element is b4
#> The name of the current list element is c3
#> $a1
#> NULL
#>
#> $b4
#> NULL
#>
#> $c3
#> NULL
iwalk(lst,(x,y) cat("The name of the current list element is", y, "n"))
#> The name of the current list element is a1
#> The name of the current list element is b4
#> The name of the current list element is c3
创建于2022-01-18由reprex包(v2.0.1(
purrr
的imap
(和iwalk
(是很好的函数。
在基本R中,您可以使用注释中已经提到的任何apply
函数来执行此操作。这是一个使用Map
-的
Map(function(x, y) sprintf('List name is %s and sum to %d', y, sum(x)),
lst, names(lst))
#$a1
#[1] "List name is a1 and sum to 68"
#$b4
#[1] "List name is b4 and sum to 51"
#$c3
#[1] "List name is c3 and sum to 782"