在R中从一种货币转换为另一种货币的功能

Function to convert from one currency to another currency in R

鉴于以下情况,从 1 美元到

我将如何编写函数将一种货币转换为另一种货币?

该函数应该像这样工作 - amount 是数字,fromto 是字符串:

currency(amount = 1, from = 'usd', to = 'euro')
## [1] 8.7

我唯一能想到的就是写很多 if 语句,但是对于所有这些可能的货币来说,这似乎太乏味了 conversions/combinations。

我也在考虑在我的函数中创建一个命名向量,如下所示:c('euro' = 0.93, 'peso' = 24.71, 'franc' = 0.98, ...) 等等,以显示从 1 美元到这些货币的兑换率。但仍然不确定如何编写一个函数来处理所有这些货币转换(美元、欧元、比索、法郎、奥地利元、新西兰元、加元)。

这是一个函数,它确实存在轻微的舍入误差,但只需要分辨率更高的数字来减少该误差 - 我的值来自 google 对每种货币 10000 美元的搜索。如果您想自动更新值,您还可以查看从网络上抓取值的包(rvest?)。

currencyCon <- function(x, from = "USD", to = "EUR"){
  # assign values: 1 usd in each currency 
  values <- c(1.000000, 0.927985, 0.810100, 107.624500)
  # names attribute 
  names(values) <- c("USD", "EUR", "GBP", "YEN")
  # calculate (convert from into USD, and divide to)
  values[to] / (values[from] / x)
}

# Testing 
currencyCon(1, "USD", "EUR")
currencyCon(1, "EUR", "EUR")
currencyCon(1, "GBP", "YEN")

这个returns

 > currencyCon(1, "USD", "EUR")
 EUR 
 0.927985
 > currencyCon(1, "EUR", "EUR")
 EUR 
 1 
 > currencyCon(1, "GBP", "YEN")
 YEN 
 132.8534

以下只是对 rg255 的回答稍作修改。您可以使用 {quantmod} 或其他软件包来确保您的货币换算率是最新的(参见 thread)。

library(quantmod)
library(tidyverse)

possible_countries <- c("USD", "EUR", "GBP", "JPY")

rates <- tibble(from = "USD", 
                       to = possible_countries) %>% 
  mutate(getQuote(paste0(from, to, "=X")) %>% 
           select(rate = Last))

currencyCon <- function(x, 
                        from = "USD", 
                        to = "EUR", 
                        lookup = rates){
  # assign values: 1 usd in each currency 
  values <- lookup$rate
  # names attribute 
  names(values) <- lookup$to
  # calculate (convert from into USD, and divide to)
  values[to] / (values[from] / x)
}

crossing(from = possible_countries, 
         to = possible_countries) %>% 
  mutate(start_amount = 10) %>% 
  mutate(amount_converted = currencyCon(start_amount, from, to))
#> # A tibble: 16 x 4
#>    from  to    start_amount amount_converted
#>    <chr> <chr>        <dbl>            <dbl>
#>  1 EUR   EUR             10          10     
#>  2 EUR   GBP             10           8.61  
#>  3 EUR   JPY             10        1328.    
#>  4 EUR   USD             10          12.1   
#>  5 GBP   EUR             10          11.6   
#>  6 GBP   GBP             10          10     
#>  7 GBP   JPY             10        1542.    
#>  8 GBP   USD             10          14.1   
#>  9 JPY   EUR             10           0.0753
#> 10 JPY   GBP             10           0.0649
#> 11 JPY   JPY             10          10     
#> 12 JPY   USD             10           0.0915
#> 13 USD   EUR             10           8.23  
#> 14 USD   GBP             10           7.09  
#> 15 USD   JPY             10        1093.    
#> 16 USD   USD             10          10

reprex package (v2.0.0)

于 2021-05-14 创建