I am trying to solve the following problem in R. I have a data frame with 4 columns: currency_1_amt
, currency_1_denom
, currency_2_amt
, currency_2_denom
. Here are a few rows from this table
|----------------|------------------|----------------|------------------|
| currency_1_amt | currency_1_denom | currency_2_amt | currency_2_denom |
|----------------|------------------|----------------|------------------|
| 100 | USD | 620 | CNY |
| 500 | CNY | 80.55 | USD |
| 80.55 | INR | 1 | USD |
| 100 | INR | 9.67 | CNY |
I am trying to compute a notional value for each row:
If
currency_1_denom == "USD"
thennotional value=currency_1_amt
.If
currency_2_denom == "USD"
thennotional value=currency_2_amt
.If neither
currency_1_denom == "USD"
norcurrency_1_denom == "USD"
thennotional_value = currency_1_amt * exchange_rate_of_currency_1_to_USD
(I have another column in the data frame with the relevant exchange rate.
I am not sure how to do this in R without looping through each row. Heer is some pseudo R code that I thought up for doing this
result = numeric(length(df))
for(j in 1:length(df)) {
if(df[j,"currency_1_denom"] == "USD")
result[j] = currency_1_amt
else if(df[j,"currency_2_denom"] == "USD")
result[j] = currency_2_amt
else
result[j] = currency_1_amt * lookup_exchange_rate(currency_1_denom)
Is there a better (e.g. vectorized) way of accomplishing my task?
Recreating your data:
Creating a sample exchange rate just to run the example:
Using
ifelse
: