Is there a dictionary functionality in R

后端 未结 4 926
甜味超标
甜味超标 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:14

    In that vectors, matrices, lists, etc. behave as "dictionaries" in R, you can do something like the following:

    > (x <- structure(c(5,2),names=c("a","b"))) ## "dictionary"
    a b 
    5 2 
    > (result <- outer(x,x,function(x1,x2) x1^2+x2))
       a  b
    a 30 27
    b  9  6
    > result["b","a"]
    [1] 9
    

    If you wanted a table as you've shown in your example, just reshape your array...

    > library(reshape)
    > (dfr <- melt(result,varnames=c("x1","x2")))
      x1 x2 value
    1  a  a    30
    2  b  a     9
    3  a  b    27
    4  b  b     6
    > transform(dfr,val1=x[x1],val2=x[x2])
      x1 x2 value val1 val2
    1  a  a    30    5    5
    2  b  a     9    2    5
    3  a  b    27    5    2
    4  b  b     6    2    2
    

提交回复
热议问题