In R, how do I fill elements of a vector conditionally with respect to elements of another vector of equal length?

Viewed 20

I have a vector, purity, which contains the purities (as character strings) of 10,000 gold nuggets.

purity <- sample(c("pure","high","medium","low"), 10000, replace = TRUE) 

I would like to generate a second vector, 'coef', such that the value of element n in coef is dependent on the value of element n in purity, with "pure," "high,""medium," and "low" in purity corresponding to 1.0, 0.8, 0.5, and 0.2, in coef, respectively.

Below is a pair of vectors, both manually generated and length=5, illustrating my goal.

    > purity <- c("medium", "high", "low", "high", "pure")
    > coef   <- c( 0.5,      0.8,    0.2,   0.8 ,   1.0)     #spaces added for legibility
    > purity
    [1] "medium" "high"   "low"    "high"   "pure"     
    > coef
    [1] 0.5 0.8 0.2 0.8 1.0

How do I automate this process?

1 Answers

We may use match or a named vector for replacement. The purity and coef are the key/value pairs that are used to match with the longer vector 'purity1'. When we use setNames, it creates a named vector on the coef, which will be used in matching with the corresponding values of 'purity1' to return the values 'coef' corresponding to that match.

out <- unname(setNames(value, key)[purity])

-checking the output

> head(purity)
[1] "low"    "pure"   "pure"   "low"    "medium" "high"  
> head(out)
[1] 0.2 1.0 1.0 0.2 0.5 0.8

where

purity <- sample(c("pure","high","medium","low"), 10000, replace = TRUE) 
key <- c("low", "medium", "high",  "pure")
value   <- c(0.2, 0.5,  0.8, 1.0) 
Related