Creating a vector in R (Associative array)

Viewed 180

I know I can create an array in R like this:

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

what I have is a list like this:

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

what i want ot to create and associative array

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

then latter on I can update the array AA("STD")=1 or whatever

2 Answers

You can try -

traits <- factor(letters[1:3])
AA <- setNames(numeric(length(x)), x)
AA

#a b c 
#0 0 0 

We could try

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

data

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