Is there a dictionary functionality in R

后端 未结 4 920
甜味超标
甜味超标 2020-12-01 12:21

Is there a way to create a \"dictionary\" in R, such that it has pairs? Something to the effect of:

x=dictionary(c(\"Hi\",\"Why\",\"water\") , c(1,5,4))
x[\         


        
4条回答
  •  一向
    一向 (楼主)
    2020-12-01 13:11

    See my answer to a very recent question. In essence, you use environments for this type of functionality.

    For the higher dimensional case, you may be better off using an array (twodimensional) if you want the easy syntax for retrieving the result (you can name the rows and columns). As an alternative,you can paste together the two keys with a separator that doesn't occur in them, and then use that as a unique identifier.

    To be specific, something like this:

    tmp<-data.frame(x=c("a", "b"), val=c(5,2))
    tmp2<-outer(seq(nrow(tmp)), seq(nrow(tmp)), function(lhs, rhs){tmp$val[lhs] + tmp$val[rhs]})
    dimnames(tmp2)<-list(tmp$x, tmp$x)
    tmp2
    tmp2["a", "b"]
    

提交回复
热议问题