如何将整数映射到整数?

Ste*_*ini 0 r

我需要将整数映射到 R 中的整数。在 python 中,这是字典的工作

>>> a = { 4: 1, 5: 2, 6:3 }
>>> a[5]
2
Run Code Online (Sandbox Code Playgroud)

但在 R 中不存在这样的东西。向量不起作用:

 a<- c(1,2,3)
> a
[1] 1 2 3
> names(a) <- c(5,6,7)
> a
5 6 7 
1 2 3 
> a[[5]]
Error in a[[5]] : subscript out of bounds

Run Code Online (Sandbox Code Playgroud)

列表也不起作用

> a<- list(1,2,3)
> a
[[1]]
[1] 1

[[2]]
[1] 2

[[3]]
[1] 3

> names(a) <- c(4, 5, 6)
> a
$`4`
[1] 1

$`5`
[1] 2

$`6`
[1] 3

> a[[6]]
Error in a[[6]] : subscript out of bounds
Run Code Online (Sandbox Code Playgroud)

Sté*_*ent 5

R中有一些字典

我会建议hashmap你的情况下的包。

library(hashmap)
H <- hashmap(c(2, 4, 6), c(99, 999, 9999))
H
##   (numeric) => (numeric)     
## [+2.000000] => [+99.000000]  
## [+4.000000] => [+999.000000] 
## [+6.000000] => [+9999.000000]
H[[4]]
# [1] 999
Run Code Online (Sandbox Code Playgroud)

如果你想要“真”整数:

H <- hashmap(c(2L, 4L, 6L), c(99L, 999L, 9999L))
H
## (integer) => (integer)
##       [2] => [99]     
##       [4] => [999]    
##       [6] => [9999] 
Run Code Online (Sandbox Code Playgroud)