Alternative to loop ifelse() for vector data

后端 未结 2 1739
后悔当初
后悔当初 2021-01-22 12:56

I have a price dataframe dat and a second dataframe with currencies cur. What i want to do is to transform every non-EUR price in dat into

相关标签:
2条回答
  • 2021-01-22 13:16

    I think this would be much easier as a merge/join operation. Using tidy verse you can do

    library(tidyverse)
    dat <- read_table("Nation   Price
    AT       10
    AT       12
    BE       15
    BG       30
    BG       40
    CZ       200")
    cur <- read_table("Nation Rate
    BG     0.51
    CZ     0.03918")
    
    
    dat %>% left_join(cur) %>% 
      mutate(Rate=coalesce(Rate, 1)) %>%
      mutate(EPrice = Price * Rate)
    

    The only trick here is to change the Rate for those nations not in the cur table to 1.

    0 讨论(0)
  • 2021-01-22 13:35

    The problem with your code is that you are comparing a vector against a character in if (dat$Nation == cur$Nation[i]), so the error tells you that it will only compare the first element of dat$Nation with cur$Nation[i].

    In R, for-loops are often not necessary (and slow). You could do for example the following:

    dat$conv <- cur$Rate[match(dat$Nation,cur$Nation)] # add the conversion factor
    dat$PriceE <- ifelse(is.na(dat$conv), dat$Price, dat$Price * dat$conv)
    dat$conv <- NULL
    

    Output:

      Nation Price PriceE
    1     AT    10 10.000
    2     AT    12 12.000
    3     BE    15 15.000
    4     BG    30 15.300
    5     BG    40 20.400
    6     CZ   200  7.836
    

    Hope this helps!

    0 讨论(0)
提交回复
热议问题