Robin Kohrs
Robin Kohrs

Reputation: 697

Create list in R with the names and values coming from another list

So the question is formunlated really badly, but what I want to achieve is the following: I have the following list:

list(a = data.frame(foo=1:10, bar=11:20), b = data.frame(foo=1:10, bar=11:20))

what I now want to create is another list that has the content as:

(list(a=c("foo", "bar"), b=c("foo", "bar")))
$a
[1] "foo" "bar"

$b
[1] "foo" "bar"

But obviously I don't want to hardcode it. I guess there is some more or less easy answer, but I just can't think of any at the moment. Named list and assigning names to objects still confuses me a lot in R. So any help would be super appreciated:)

Upvotes: 0

Views: 683

Answers (2)

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193497

Assuming your original list is "l", you can do:

lapply(l, names)
# $a
# [1] "foo" "bar"
# 
# $b
# [1] "foo" "bar"

From ?names, you get the description: "Functions to get or set the names of an object."

The names of the data.frames in your original list are extracted with this, and lapply preserves the names of the original list.

Upvotes: 3

akrun
akrun

Reputation: 886938

An option with tidyverse

library(purrr)
map(l, names)

-output

#$a
#[1] "foo" "bar"

#$b
#[1] "foo" "bar"

Upvotes: 1

Related Questions