How to replace values โโwith a table in R
I have two data frames: one with "encoded" values โโand the other that acts like a dictionary:
> head( encoded_values ) value 1 2 1 3 > head( dict ) id name 1 foo 2 bar 3 baz I want to replace the values โโin the first data frame with "decoded" values โโby looking at the second data frame. This should be the result of:
> head( encoded_values ) foo bar foo baz I found many similar posts, but nothing specific in my case. This may be a fairly common operation, but I am very new to R and have pretty much lost all the features that I have tried so far (none of them worked).
Thank you very much.
This is what match (note, much faster than merge ):
dict[match(encoded_values$value, dict$id), 2, drop=F] creates (we need drop=F , so instead of a vector, a data.frame , since we select only one column):
name 1 foo 2 bar 1.1 foo 3 baz match returns the location of the values โโin the first argument in the second argument. You can then use this to index the second argument.
Actually replace:
encoded_values$value <- with(dict, name[match(encoded_values$value, id)]) Note , in this simple case, since your identifiers match the line numbers in the dict , you can also do:
dict[encoded_values$value, 2, drop=F] but this only works because of the special nature of the id variable in the dict (starts at 1, increments by 1 each).