Home > front end >  R join a table column from a vector
R join a table column from a vector

Time:07-06

I would like to get the corresponding values of a vector in a table from a column in another column. (just look below)

example:

Vector:

v = c('A', 'B', 'C')

Table :

# key     Value
 'C'        3
 'A'        1
 'B'        2

When I give the vector v (A, B, C) I want to get back the corresponding values in the good order 1, 2, 3.

In reality, the vector is the rownames of a dataset, and I need to replace it with the corresponding values.

I was thinking about using the left_join function from Dplyr but I would need 2 tables for this.

Thanks for your help

CodePudding user response:

A possible solution in base R:

df$Value[match(v, df$key)]

#> [1] 1 2 3

Using dplyr:

library(dplyr)

df %>% 
  mutate(x = Value[match(v, key)]) %>% 
  pull(x)

#> [1] 1 2 3
  • Related