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

6
  • 2
    Can't convert without exchange rates. Commented Dec 6, 2021 at 15:40
  • Forgot to add them here, no worries , I'm just looking for a different way than a for loop Commented Dec 6, 2021 at 15:42
  • 1
    I'd suggest to merge the exchange rates to your df and then simply do df$USD_salary = df$salary * df$convert Commented Dec 6, 2021 at 15:44
  • I have 30k rows in the dataframe , Commented Dec 6, 2021 at 15:47
  • having 30k rows is not impeditive to using Maels answer, which is most likely the most concise approach Commented Dec 6, 2021 at 15:49

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.