使用向量中的字符来命名列表中的对象

问题描述 投票:0回答:2

我有一个字符向量。

char_vec = c("hello","world","foo","bar")

如何从该向量中分配一个字符(或索引)来命名列表中的对象?

所以与其做

list("hello"=1,"world"=2)

$hello  1
$world  2

我想做的事:

list(as.character(char_vec[1])=1,as.character(char_vec[2])=2)

为此我得到一个错误

Error in parse(text = x, srcfile = src): <text>:1:31: unexpected '='
1: list(as.character(char_vec[1])=
                                  ^
Traceback:
r list vector character
2个回答
2
投票

我们可以使用

setNames

setNames(as.list(seq_along(char_vec)), char_vec)

-输出

$hello
[1] 1

$world
[1] 2

$foo
[1] 3

$bar
[1] 4

1
投票
char_vec = c("hello","world","foo","bar")
setNames(list(1,2), char_vec[1:2])
#> $hello
#> [1] 1
#> 
#> $world
#> [1] 2
© www.soinside.com 2019 - 2024. All rights reserved.