Access and preserve list names in lapply function Access and preserve list names in lapply function r r

Access and preserve list names in lapply function


I believe that lapply by default keeps the names attribute of whatever you are iterating over. When you store the names of myList in n, that vector no longer has any "names". So if you add that back in via,

names(n) <- names(myList)

and the use lapply as before, you should get the desired result.

Edit

My brains a bit foggy this morning. Here's another, perhaps more convenient, option:

sapply(n,FUN = ...,simplify = FALSE,USE.NAMES = TRUE)

I was groping about, confused that lapply didn't have a USE.NAMES argument, and then I actually looked at the code for sapply and realized I was being silly, and this was probably a better way to go.


the setNames function is a useful shortcut here

mylist <- list(a = TRUE, foo = LETTERS[1:3], baz = 1:5)n <- names(mylist)mynewlist <- lapply(setNames(n, n), function(nameindex) {mylist[[nameindex]]})

which preserves the names

> mynewlist$a[1] TRUE$foo[1] "A" "B" "C"$baz[1] 1 2 3 4 5


Building on joran's answer, and precising it:

The sapply(USE.NAMES=T) wrapper will indeed set as names of the final result the values of the vector you are iterating over (and not its names attribute like lapply), but only if these are characters.

As a result, passing indices will not help. If you want to pass indexes with sapply, you need to resort to some (ugly) casting:

sapply(as.character(c(1,11)), function(i) TEST[[as.numeric(i)]], USE.NAMES = TRUE)

In this case, a cleaner solution is to directly set and use names of your original object. Here is an exhaustive list of solutions:

TEST <- as.list(LETTERS[1:12])### lapply #### Not working because no name attributelapply(c(1,11), function(i) TEST[[i]])## working but cumbersomeindex <- c(1,11)names(index) <- indexlapply(index, function(i) TEST[[i]])### sapply #### Not working because vector elements are not stringssapply(c(1,11), function(i) TEST[[i]], simplify = F) ## Working with the casting tricksapply(as.character(c(1,11)), function(i) TEST[[as.numeric(i)]], simplify = F)## Cleaner, using names with sapply:names(TEST) <- LETTERS[26:15] sapply(names(TEST)[c(1,11)], function(name) TEST[[name]], simplify = F)