Dictionaries and pairs

前端 未结 5 1995
时光取名叫无心
时光取名叫无心 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:16

    R matrices allow you to do this. There are both sparse and dense version. I beleive the tm-package uses a variation on sparse matrices to form its implementation of dictionaries. This shows how to extract the [i,j] elements of matrix M where [i,j] is represented as a a two-column matrix.

    M<- matrix(1:20, 5, 5)
    ij <- cbind(sample(1:5), sample(1:5) )
    
    > ij
         [,1] [,2]
    [1,]    4    4
    [2,]    1    2
    [3,]    5    3
    [4,]    3    1
    [5,]    2    5
    > M[ij]
    [1] 19  6 15  3  2
    

    @Justin also points out that you could use lists which can be indexed by position:

     L <- list( as.list(letters[1:5] ), as.list( paste(2,letters[1:5] ) ) )
    
    > L[[1]][[2]]
    [1] "b"
    > L[[2]][[2]]
    [1] "2 b"
    

提交回复
热议问题