Функция конвертации валют, если выписка не совпадает с именами - PullRequest
0 голосов
/ 26 ноября 2018

Я довольно новичок в R, и я в настоящее время играю с функциями, и если операторы

, поэтому я сделал data.frame следующим образом:

cash=c(50, 480, 45, 1000)
currency=c("chf", "eur", "gbp", "twd")
cash_tot=data.frame(cash, currency)
cash_tot

и яЯ хотел бы создать своего рода функцию «конвертации наличных» только для валют, совпадающих с валютами CHF и EUR.Поэтому я попробовал следующий код:

converter=function(x){
 for(currency in x){
   if (currency=="chf"){
   return(cash)
}
else if (currency=="eur"){
  return(cash/1.13)
}
  else{
  print("Calculate it yourself :)")
  }
  }
}

converter(cash_tot)

Все, что я получу взамен, это

[1] "Calculate it yourself :)"
Warning messages:
1: In if (currency == "chf") { :the condition has length > 1 and only the first element will be used
2: In if (currency == "eur") { :the condition has length > 1 and only the first element will be used
3: In if (currency == "chf") { :the condition has length > 1 and only the first element will be used

кто-нибудь, кто мог бы помочь?Заранее прошу прощения, если это глупый вопрос, ахах:)

1 Ответ

0 голосов
/ 27 ноября 2018

этот код на самом деле работает:

########################################

amount=c(50, 480, 45, 5000)
currency=c("chf", "eur", "gbp", "vnd")
cash2=data.frame(amount, currency)

> cash2
  amount currency
1     50      chf
2    480      eur
3     45      gbp
4   5000      vnd
> str(cash2)
'data.frame':   4 obs. of  2 variables:
 $ amount  : num  50 480 45 5000
 $ currency: Factor w/ 4 levels "chf","eur","gbp",..: 1 2 3 4

########################################

 converter=function(x){
  for(i in 1:nrow(x)){
  if (x$currency[i]=="chf"){
    x1=(x$amount[i])
    print(paste("chf",x1))
  }
  else if (x$currency[i]=="eur"){
    x2=((x$amount[i])*(1.13))
    print(paste("chf",x2))
  }
  else if (x$currency[i]=="gbp"){
    x3=((x$amount[i])*(1.28))
    print(paste("chf",x3))
  }
  else if (x$currency[i]=="vnd"){
    x4=((x$amount[i])/(22500))
    print(paste("chf",x4))
  }
  else{
    print(paste("Calculate it yourself :)", x$amount[i], x$currency[i]))
  }
  }
  return(new_cash=c(x1,x2,x3,x4))
}

converter(x=cash2)

########################################

> converter(x=cash2)
[1] "chf 50"
[1] "chf 542.4"
[1] "chf 57.6"
[1] "chf 0.222222222222222"
...