vendredi 12 janvier 2018

Alternative to loop ifelse() for vector data

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 Euro with a for() function and nested ifelse(). else a price already is EUR, the function should do nothing and return the original value into the column Price € in dat.

dat:

Nation   Price  Price€  
AT       10
AT       12
BE       15
BG       30
BG       40
CZ       200

cur:

Nation Rate
BG     0.51
CZ     0.03918

Only countries with non-EU currency are contained in cur. I used this code:

 for (i in 1:length(cur)){
  if(dat$Nation == cur$Nation[i]){
    dat$Price * cur$Rate[i]
     }
     else { }
  }

The output should be something like this:

dat:

Nation  Price  Price€
AT      10     NA
AT      12     NA
BE      15     NA
BG      30     15.3
BG      40     20.4
CZ      200    7.836

The idea is to fill NAs in the Price€ column (those are countries with € currency) - resulting from not telling the function what to do in the case of else - with values from Price after the loop finished.

 index <- is.na(dat$Price€)
 dat$Price€[index] <- dat$Price[index]

dat:

Nation  Price  Price€
AT      10     10
AT      12     12
BE      15     15
BG      30     15.3
BG      40     20.4
CZ      200    7.836

My problem here is, that R gives an error message:

Warning messages:
1: In if (dat$Nation == cur$Nation[i]) { :
the condition has length > 1 and only the first element will be used
2: In if (dat$Nation == cur$Nation[i]) { :
the condition has length > 1 and only the first element will be used

What it does is multiplying all price values with the first exchange rate (0.51) and then stopping to look for identical values for the columns Nation in both dataframes to apply a different exchange rate. This is just a simple example from my dataset. There are multiple entries for each country within the EU (n=1740).

This might sound a complicated way to do this, but I am new to R and would like to know how to fix this function or what an alternative function would be.

Cheers

Aucun commentaire:

Enregistrer un commentaire