我有一個帶有命名元素的串列,如下所示:
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
}
}
uj5u.com熱心網友回復:
也許這會有所幫助
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
uj5u.com熱心網友回復:
在purrr包中,有函式imap()和iwalk(). 他們接受一個串列和一個帶有兩個引數的函式,并將該函式應用于串列的每個元素及其索引/名稱。不同之處在于,它iwalk靜默回傳NULL并僅針對副作用執行(如果您 map over 會有所幫助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
由reprex 包(v2.0.1)于 2022-01-18 創建
uj5u.com熱心網友回復:
purrr如果您想同時訪問資料和串列名稱,則's 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"
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/414698.html
標籤:
下一篇:檢查列型別是否存在
