Dictionaries and pairs

前端 未结 5 1996
时光取名叫无心
时光取名叫无心 2021-01-17 06:53

In R I was wondering if I could have a dictionary (in a sense like python) where I have a pair (i, j) as the key with a corresponding integer value. I have not

5条回答
  •  萌比男神i
    2021-01-17 07:28

    Both named lists and environments provide a mapping, but between a character string (the name, which acts as a key) and an arbitrary R object (the value). If your i and j are simple (as they appear in your example to be, being integers), you can easily make a unique string out of the pair of them by concatenating them with some delimiter. This would make a valid name/key

    mykey <- function(i, j) {
      paste(i, j, sep="|")
    }
    
    maps <- list()
    for(i in 1: 5) {  
      for(j in 2: 4) {
        maps[mykey(i,j)] <- which.min(someVector)
      }
    }
    

    You can extract any value for a specific i and j with

    maps[[mykey(i,j)]]
    

提交回复
热议问题