Home > Mobile >  Change column with multiple values based on another column
Change column with multiple values based on another column

Time:12-07

salary <- c(5000, 3000, 2000, 1000, 5000) 
currency <- c('USD', 'EUR', 'JPY', 'CHF', 'CAD')

df <- data.frame(salary, currency)

I want to convert all the salaries to USD, so if I want to convert the 3000 to USD I will multiply 3000 by 1.12. It worked with a for loop and if statement, but I wonder if there's a faster and shorter way.

CodePudding user response:

Let's say you have a exchange rates table:

exchangeRatestoUSD = data.frame(currency = c('USD', 'EUR', 'JPY', 'CHF', 'CAD'),
                                rates = c(1, 2, 2.51, 1.14, 12))
  currency rates
1      USD  1.00
2      EUR  2.00
3      JPY  2.51
4      CHF  1.14
5      CAD 12.00

Then you can simply do:

df <- merge(df, exchangeRatestoUSD)
df$USD_salary = df$salary * df$rates

  currency salary rates USD_salary
1      CAD   5000 12.00      60000
2      CHF   1000  1.14       1140
3      EUR   3000  2.00       6000
4      JPY   2000  2.51       5020
5      USD   5000  1.00       5000
  • Related