[英]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.
在 R 中,命名列表和为对象分配名称仍然让我很困惑。 So any help would be super appreciated:)
所以任何帮助将不胜感激:)
Assuming your original list is "l", you can do:假设您的原始列表是“l”,您可以执行以下操作:
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."从
?names
中,您得到描述:“获取或设置 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.原始列表中的
data.frame
的名称由此提取,并且lapply
保留原始列表的名称。
An option with tidyverse
tidyverse
的一个选项
library(purrr)
map(l, names)
-output -输出
#$a
#[1] "foo" "bar"
#$b
#[1] "foo" "bar"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.