1

Let's say we have a following dataframe named df:

Country GDP/capita HDI
1       67426      0.92
2       46827      0.92
4       47223      0.89
3       52559      0.94

Let's also say we have a numeric named vector vec with values 1, 2, 3 and 4 and names USA, UK, Germany and France.

Given those two objects, what is the fastest way to make the dataframe look like this:

Country GDP/capita HDI
USA     67426      0.92
UK      46827      0.92
France  47223      0.89
Germany 52559      0.94

(Note that the order of the vector is 1, 2, 3, 4, while the order in the dataframe is 1, 2, 4, 3).

Tidyverse solutions preferred!

Dharman
  • 30,962
  • 25
  • 85
  • 135
J. Doe
  • 1,544
  • 1
  • 11
  • 26

2 Answers2

1

One dplyr option could be:

vec <- setNames(1:4, c("USA", "UK", "Germany", "France"))

df %>%
 mutate(Country = names(vec)[match(vec, Country)])

  Country GDP_capita  HDI
1     USA      67426 0.92
2      UK      46827 0.92
3  France      47223 0.89
4 Germany      52559 0.94
tmfmnk
  • 38,881
  • 4
  • 47
  • 67
0

You can do :

df$Country <- names(vec)[df$Country]
df

#  Country GDP.capita  HDI
#1     USA      67426 0.92
#2      UK      46827 0.92
#3  France      47223 0.89
#4 Germany      52559 0.94

If you want a tidyverse answer you can use :

tibble::enframe(vec) %>% dplyr::right_join(df, by = c('value' = 'Country'))

Or in base R :

merge(stack(vec), df, by.x = 'values', by.y = 'Country')
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213