【问题标题】:Using if functions to perform calculations across two tables - Rstudio使用 if 函数跨两个表执行计算 - Rstudio
【发布时间】:2021-09-04 10:43:39
【问题描述】:

我正在尝试使用 if 函数(除非有更好的方法!)将欧元和美元金额转换为英镑。我有两张表,一张是汇率表,一张是人们的假期消费表。

假日消费

Date<- c('01/01/2021', '02/01/2021','01/01/2021', '02/01/2021','01/01/2021', '02/01/2021','01/01/2021', '02/01/2021' )
Person <- c('Person A', 'Person B', 'Person C', 'Person A', 'Person B', 'Person C', 'Person A', 'Person B')
Amount <- c('100',  '150',  '200',  '250',  '300',  '350',  '400',  '450')
Currency <- c('GBP',    'EUR',  'USD',  'GBP',  'GBP',  'GBP',  'EUR',  'USD')

DF <- data.frame(Date, Person, Currency, Amount) 

对话率

Date<- c('01/01/2021', '01/01/2021','02/01/2021', '02/01/2021','03/01/2021', '03/01/2021','04/01/2021', '04/01/2021' )
Country <- c('EUR', 'USD',  'EUR',  'USD',  'EUR',  'USD',  'EUR',  'USD')
Rate <- c('2',  '4',    '6',    '8',    '10',   '12',   '14',   '16')


XR <- data.frame(Date, Country, Rate)

我要做的是搜索假期消费的货币列表,如果货币列显示不是英镑,则查找当天的货币兑换率并重新计算金额列。

例如,B 人在 2021 年 2 月 10 日花了 150 欧元,当天的会话率是 6,所以应该将 150 重新计算为 900,我不需要更改货币列当我稍后在此过程中重新调整表格时,无论如何都会被过滤掉。

我可以在 Excel 中使用 vlookups 和 if 函数来完成此操作,但我正在努力将其转换为 R。在 Excel 中,我在不同的选项卡上有欧盟和美元汇率,但在 R 中它是一张大表。我可以将它拆分成小表,但仍然不确定如何让 if 和 sum 以 R 格式工作。

Excel函数

=IF(D2="EUR",SUM(E2 * VLOOKUP(A2,EU!A:D,3,FALSE)),IF(D2="USD",SUM(E2* VLOOKUP(A2,USD!A:D,3,FALSE)),Spending!E2))

感谢您的建议。

【问题讨论】:

    标签: r excel if-statement calculated-columns


    【解决方案1】:

    您可以执行连接并将比率乘以金额。

    library(dplyr)
    
    DF %>%
      left_join(XR, by = c('Date', 'Currency' = 'Country')) %>%
      mutate(New_Amount = as.numeric(Amount) * as.numeric(Rate), 
             New_Amount = coalesce(New_Amount, as.numeric(Amount)))
    
    #        Date   Person Currency Amount Rate New_Amount
    #1 01/01/2021 Person A      GBP    100 <NA>        100
    #2 02/01/2021 Person B      EUR    150    6        900
    #3 01/01/2021 Person C      USD    200    4        800
    #4 02/01/2021 Person A      GBP    250 <NA>        250
    #5 01/01/2021 Person B      GBP    300 <NA>        300
    #6 02/01/2021 Person C      GBP    350 <NA>        350
    #7 01/01/2021 Person A      EUR    400    2        800
    #8 02/01/2021 Person B      USD    450    8       3600
    

    【讨论】:

    • 另一个在概念上似乎比coalesce 更简单的选项是在乘法之前将 GBP 的转换因子设置为 1
    猜你喜欢
    • 1970-01-01
    • 2020-03-28
    • 1970-01-01
    • 2011-10-21
    • 1970-01-01
    • 2018-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多