Stefano Borini
Stefano Borini

Reputation: 143795

How can I map an integer to an integer?

I need to map an integer to an integer in R. In python this is the job of a dictionary

>>> a = { 4: 1, 5: 2, 6:3 }
>>> a[5]
2

but no such thing exists in R. A vector does not work:

 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

a list doesn't work either

> 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

Upvotes: 1

Views: 274

Answers (4)

Der Gnirreh
Der Gnirreh

Reputation: 306

For good performance you use match.

k<-c(5,6,7)
v<-c(1,2,3)

x<-c(5,5,6)

v[match(x,k)] 

In fact, if your v is just 1:n it is enough to do

match(x, k)

as match returns the index in the array you are doing lookup in.

Upvotes: 2

St&#233;phane Laurent
St&#233;phane Laurent

Reputation: 84529

There are some dictionaries in R.

I would suggest the hashmap package for your case.

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

If you want "true" integers:

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

Upvotes: 5

iod
iod

Reputation: 7592

A less than optimal possible solution would be to assign the integers into position of their integers in a vector:

a[c(5:7)]<-1:3
a[6]
> [1] 2

A drawback (or benefit, depends on your needs) is that a[1] would yield an NA

Upvotes: 1

Marta
Marta

Reputation: 3162

In your last example this should work (string not numeric):

a <- list(1,2,3)
names(a) <- c(4, 5, 6)    

a[["6"]]
a[[as.character(6)]]

Upvotes: 1

Related Questions