nsa
nsa

Reputation: 565

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?

Upvotes: 2

Views: 46

Answers (2)

ThomasIsCoding
ThomasIsCoding

Reputation: 101099

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

Upvotes: 2

akrun
akrun

Reputation: 886948

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"))

Upvotes: 2

Related Questions