[R] Generate a vector of values, given a vector of keys and a table?

Bert Gunter bgunter.4567 at gmail.com
Fri Sep 11 07:30:50 CEST 2015


?match

as in:

> y <- lk_up[match(x,lk_up[,"key"]),"val"]
> y
 [1] "10000" "10000" "10000" "10000" "15000" "15000" "20000"
 [8] "20000" "20000" "20000"



Bert



Bert Gunter

"Data is not information. Information is not knowledge. And knowledge
is certainly not wisdom."
   -- Clifford Stoll


On Thu, Sep 10, 2015 at 10:04 PM, David Wolfskill <r at catwhisker.org> wrote:
> I apologize in advance: I must be overlooking something quite simple,
> but I'm failing to make progress.
>
> Suppose I have a "lookup table":
>
> Browse[2]> dput(lk_up)
> structure(c("1.1", "1.9", "1.4", "1.5", "1.15", "10000", "10000",
> "15000", "20000", "25000"), .Dim = c(5L, 2L), .Dimnames = list(
>     NULL, c("key", "val")))
> Browse[2]> lk_up
>      key    val
> [1,] "1.1"  "10000"
> [2,] "1.9"  "10000"
> [3,] "1.4"  "15000"
> [4,] "1.5"  "20000"
> [5,] "1.15" "25000"
>
> and a vector whose elements correspond with the "key" column of the
> table:
>
> Browse[2]> dput(x)
> c("1.9", "1.9", "1.1", "1.1", "1.4", "1.4", "1.5", "1.5", "1.5",
> "1.5")
> Browse[2]> x
>  [1] "1.9" "1.9" "1.1" "1.1" "1.4" "1.4" "1.5" "1.5" "1.5" "1.5"
> Browse[2]>
>
> Is there a (relatively) simple (i.e., not explicitly looping) construct
> that will yield a vector of the same size and shape as "x", but contain
> the "value" entries from the lookup table (preserving the sequence: the
> 1st entry of the result must correspond to the 1st entry of the list of
> keys) -- in the current example:
>
> Browse[2]> dput(y)
> c("10000", "10000", "10000", "10000", "15000", "15000", "20000",
> "20000", "20000", "20000")
> Browse[2]> y
>  [1] "10000" "10000" "10000" "10000" "15000" "15000" "20000" "20000"
> "20000" "20000"
> Browse[2]>
>
> I am (unfortunately) presently limited to R-3.0.2.
>
> Thanks....
>
> Peace,
> david
> --
> David H. Wolfskill                              r at catwhisker.org
> Those who would murder in the name of God or prophet are blasphemous cowards.
>
> See http://www.catwhisker.org/~david/publickey.gpg for my public key.
>
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list