I have two vectors and I want to create a list in R where one vector are the keys and the other the values. I thought that I was going to find easily the answer in my books
Another serious option here , is to use data.table. Which use the key to sort your structure and it is very fast to access elements specially when you have a large numbers . Here an example:
library(data.table)
DT <- data.table(xx = 1:1e6,
k = paste0("key", 1:1e6),key="k")
Dt is a data.table with 2 columns , where I set the column k as a key.
DT
xx k
1: 1 key1
2: 10 key10
3: 100 key100
4: 1000 key1000
5: 10000 key10000
---
999996: 999995 key999995
999997: 999996 key999996
999998: 999997 key999997
999999: 999998 key999998
1000000: 999999 key999999
Now I can access my data.table using the key like this:
DT['key1000']
k xx
1: key1000 1000
Here a benchmarking comparing the data.table solution to a named vector:
vals <- 1:1000000
DT <- data.table(xx = vals ,
k = paste0("key", vals),key="k")
keys <- paste0("key", vals)
names(vals) <- keys
library(microbenchmark)
microbenchmark( vals["key42"],DT["key42"],times=100)
Unit: microseconds
expr min lq median uq max neval
vals["key42"] 111938.692 113207.4945 114924.010 130010.832 361077.210 100
DT["key42"] 768.753 797.0085 1055.661 1067.987 2058.985 100