head( ...">

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.

+6
source share
2 answers

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).

+7
source

Just in case your encoded_values is a multi-columns matrix, you can also try this,

 words_mapped <- matrix(with(dict, name[match(encoded_values[ ,1:ncol(encoded_values)], id)]), nrow = nrow(encoded_values)) 

this will also work for a single column in your problem. Hooray!

0
source

Source: https://habr.com/ru/post/974172/


All Articles