0

我有以下代码将我的数据框中的相关列从任何货币转换为美元:

df %>% 
  mutate_at(vars(contains('cost_AUD')), list(~ . * ER_AUD_USD )) %>%
  mutate_at(vars(contains('cost_GBP')), list(~ . * ER_GBP_USD )) %>%
  mutate_at(vars(contains('cost_EUR')), list(~ . * ER_EUR_USD ))

我的数据框看起来像这样(但有更多列):

         date     cost_AUD_d   cost_CAD_e   cost_AUD_f   ER_AUD_USD   ER_CAD_USD
1  2016-01-01          80.18         5.95         4.83         0.70         0.69
2  2016-02-01          85.72         5.12         3.98         0.71         0.67
3  2016-03-01          67.33         5.12         5.02         0.75         0.72
4  2016-04-01          77.42         5.11         4.55         0.77         0.73
5  2016-05-01          75.40         5.54         4.92         0.73         0.70

有一个更好的方法吗?由于列的名称恰当,因此只需将每个价格所在的货币与汇率列的中间部分(即 cost_*** 和 ER_***_USD)进行匹配。有没有办法将 switch 语句与 mutate 结合起来。

4

1 回答 1

0

这是一种可能的方法:

#Please include all currencies that you have
currency <- c('AUD', 'GBP', 'EUR')
#Loop over each of them
do.call(cbind, lapply(currency, function(x) {
    #Find all the columns with that currency
    group_cols <- grep(paste0('cost_', x), names(df))
    #Get the exhange rate column
    col_to_multiply <- grep(paste0('ER_', x), names(df))
    #Repeat the exchange rate column same as total columns and multiply
    df[group_cols] * df[rep(col_to_multiply, length(group_cols))]
}))

或与purrr::map_dfc

purrr::map_dfc(currency, ~{
   group_cols <- grep(paste0('cost_', .x), names(df))
   col_to_multiply <- grep(paste0('ER_', .x), names(df))
   df[group_cols] * df[rep(col_to_multiply, length(group_cols))]
})  
于 2020-01-06T03:29:01.557 回答