Reputation: 697
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
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.frame
s in your original list are extracted with this, and lapply
preserves the names of the original list.
Upvotes: 3
Reputation: 886938
An option with tidyverse
library(purrr)
map(l, names)
-output
#$a
#[1] "foo" "bar"
#$b
#[1] "foo" "bar"
Upvotes: 1