How do I convert one value into a corresponding one from a conversion table in R?

233 Views Asked by At

I apologize if the phrasing of my question didn't make much sense, but hopefully my explanation will help.

Say I have a dataframe, ex, which looks like this:

  geneID sample1 sample2
1      1      18       2
2     10       6      17
3    100       9      12

And a corresponding table, convtab, that looks like this:

  geneID genesymbol
1      1       A1BG
2     10       NAT2
3    100        ADA

The goal here is that for every geneID in ex, if it matches a value in convtab$geneID, replace it with the corresponding value from convtab$genesymbol in the same row.

For example, the value in [1,1] of ex, 1, would be replaced with A1BG.

While I could do it manually with this example set, my actual set of data is much larger so I would have no chance of changing the values manually.

I would really appreciate the help!

2

There are 2 best solutions below

0
On BEST ANSWER

As noted in the comments, this can be done as:

 ex$geneID <- convtab$genesymbol[match(ex$geneID, convtab$geneID)]
0
On

Using dplyryou could left_join the data.frames:

library(dplyr)

ex %>%
  left_join(rep, by=("geneID")) %>%
  select(-geneID, geneID=genesymbol)

returns

# A tibble: 3 x 3
  sample1 sample2 geneID
    <dbl>   <dbl> <chr> 
1      18       2 A1BG  
2       6      17 NAT2  
3       9      12 ADA