【问题标题】:Creating a vector in R (Associative array)在 R 中创建一个向量(关联数组)
【发布时间】:2021-08-30 00:22:30
【问题描述】:

我知道我可以像这样在 R 中创建一个数组:

     vec <- c(a=1,b=2,c=3)
     vec["b"]
     #b 
     #2

我有一个这样的列表:

> traits
[1] STD V1  V2  V3  W1  W2  W3 
Levels: STD V1 V2 V3 W1 W2 W3

我想要创建的和关联数组

    AA<- c(STD=0,V1=0,V2=0,V3=0,W1=0,W2=0,W3=0)

然后我可以更新数组 AA("STD")=1 或其他任何内容

【问题讨论】:

    标签: r arrays list associative-array


    【解决方案1】:

    我们可以试试

    setNames(rep(0, length(traits)), levels(traits)[traits])
    STD  V1  V2  V3  W1  W2  W3 
      0   0   0   0   0   0   0 
    

    数据

    traits <- factor(c("STD", "V1", "V2", "V3", "W1", "W2", "W3"))
    

    【讨论】:

      【解决方案2】:

      你可以试试-

      traits <- factor(letters[1:3])
      AA <- setNames(numeric(length(x)), x)
      AA
      
      #a b c 
      #0 0 0 
      

      【讨论】:

        猜你喜欢
        • 2013-11-16
        • 2018-09-13
        • 1970-01-01
        • 1970-01-01
        • 2012-12-23
        • 1970-01-01
        • 1970-01-01
        • 2016-11-15
        • 1970-01-01
        相关资源
        最近更新 更多