给出以下信息,从1美元到
我如何编写将一种货币转换为另一种货币的函数?
该函数应该像这样工作-amount
是数字,from
和to
是字符串:
currency(amount = 1, from = 'usd', to = 'euro')
## [1] 8.7
我唯一能想到的就是编写大量的if语句,但是对于所有这些可能的货币转换/组合来说,这似乎太繁琐了。
我还考虑在函数中创建一个命名矢量,如下所示:c('euro' = 0.93, 'peso' = 24.71, 'franc' = 0.98, ...)
等等,以显示从1美元到这些货币的转换率。但是仍然不确定如何编写一个函数来说明所有这些货币转换(美元,欧元,比索,法郎,奥地利元,新西兰元,加拿大元)。
答案 0 :(得分:0)
这是一个函数,它确实会遇到轻微的舍入误差,但是只需要具有更高分辨率的数字来减小该误差-我的值来自于Google搜索每种货币的10000美元。如果您想保持值的自动更新,您还可以查看从Web抓取值的软件包(是否为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")
这将返回
> currencyCon(1, "USD", "EUR")
EUR
0.927985
> currencyCon(1, "EUR", "EUR")
EUR
1
> currencyCon(1, "GBP", "YEN")
YEN
132.8534
答案 1 :(得分:0)
下面只是对 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 年 5 月 14 日创建