简体   繁体   中英

How to succinctly name all elements of several lists the same when the lists are nested in an R list?

Sometimes I come across this instance in R:

L <- list()
L[[1]] <- list()
L[[2]] <- list()
L[[1]][[1]] <- 1
L[[1]][[2]] <- 2
L[[2]][[1]] <- 1
L[[2]][[2]] <- 2

Then I want to name all elements of the nested lists in L the same. I usually do something like this:

L <- lapply(L, function(x){names(x) <- c("One", "Two"); x})

However, this looks kind of awful and I'm sure there has to be a better way. Does anyone know a more elegant way?

Instead of doing two step process, we can use the wrapper setNames

L <- lapply(L, setNames, c("One", "Two"))

Or similar option with tidyverse

library(purrr)
library(dplyr)
map(L, set_names, c("One", "Two"))

Here is another option with Map (but not as concise as lapply by @akrun's answer )

> Map(setNames, L, rep(list(c("One", "Two")), length(L)))
[[1]]
[[1]]$One
[1] 1

[[1]]$Two
[1] 2


[[2]]
[[2]]$One
[1] 1

[[2]]$Two
[1] 2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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