Get list names in a for loop

In PHP, you can access array names and values ​​in a for loop with

foreach ( $array as $key => $value ) {

Is there anything comparable in R when a loop occurs over named lists?

+5
source share
3 answers

Using some dummy data and a silly contrived example

ll <- list(A = 1:10, B = LETTERS[1:10], C = letters[1:10])

You can lapply()by element indices ll:

out <- lapply(seq_along(ll),
           function(ind, list, names) {
               paste(names[ind], "=", paste(list[[ind]], collapse = ", "))
           }, list = ll, names = names(ll))

R> out
[[1]]
[1] "A = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10"

[[2]]
[1] "B = A, B, C, D, E, F, G, H, I, J"

[[3]]
[1] "C = a, b, c, d, e, f, g, h, i, j"

or for()by list:

ll2 <- vector("list", length(ll))
nams <- names(ll)
for(i in seq_along(ll)) {
    ll2[[i]] <- paste(nams[i], "=", paste(ll[[i]], collapse = ", "))
}
ll2

R> ll2
[[1]]
[1] "A = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10"

[[2]]
[1] "B = A, B, C, D, E, F, G, H, I, J"

[[3]]
[1] "C = a, b, c, d, e, f, g, h, i, j"
+8
source

To get list names, you simply use names(list).

ll <- list(A = 1:10, B = LETTERS[1:10], C = letters[1:10])
names(ll)
#[1] "A" "B" "C"

Most * apply functions return values ​​that are appropriately named if the name was named first.

sapply(ll, max)
#   A    B    C 
#"10"  "J"  "j" 
+3
source

:

for (name in names(myList)) {
    print(name)
    print(myList[[name]])
}

: . .

0

All Articles