[英]ifelse statement with calculation in R
I'm trying to write code to convert different currencies to EUR.我正在尝试编写代码将不同的货币转换为欧元。
The current dataset(df) looks like this.当前数据集(df)看起来像这样。
Currency![]() |
Price![]() |
---|---|
CHF![]() |
1000 ![]() |
DKK![]() |
20000 ![]() |
My goal is mutate a column to show how much they are in EUR.我的目标是改变一列以显示它们有多少欧元。
Currency![]() |
Price![]() |
EUR![]() |
---|---|---|
CHF![]() |
1000 ![]() |
980 ![]() |
DKK![]() |
20000 ![]() |
2600 ![]() |
It seems easy but I can't really figure it out... Can anyone help me with this?这看起来很容易,但我真的想不通......有人可以帮我吗?
I tried a code with ifelse.我用 ifelse 尝试了一段代码。
df <- df %>%
mutate(converted = ifelse(Currency == "CHF", Price*0.98,
ifelse(Currency == "EUR", Price*1,
ifelse(Currency == "DKK", Price*0.13))))
It returns this error message.它返回此错误消息。
Error: Problem with
mutate()
columnconverted
.错误:问题与
mutate()
列converted
。 [34mℹ[39mconverted = ifelse(...)
.[34mℹ[39m
converted = ifelse(...)
。 [31m✖[39m non-numeric argument to...[31m✖[39m 非数字参数...
I've also tried this.我也试过这个。
df <- df %>%
mutate(converted = if(Currency == "CHF"){
Price*0.98
} else if (Currency == "DKK"){
Price*0.13
} else {
Price*1
}
It returns another error message.它返回另一条错误消息。
Error in parse(text = x, srcfile = src): <text>:9:0: unexpected end of input 7: Price*1 8: } ^
解析错误(文本= x,srcfile = src):<文本>:9:0:输入7的意外结束:价格* 1 8:} ^
case_when
vs nested ifelse
case_when
与嵌套ifelse
As mentioned in the replies, case_when()
will make your code easier to read and write:正如回复中提到的,
case_when()
将使您的代码更易于阅读和编写:
library(dplyr)
df <- tibble::tribble(
~Currency, ~Price,
"CHF", 1000,
"DKK", 20000
)
euro_prices <- df %>%
mutate(
converted = case_when(
Currency == "CHF" ~ Price * 0.98,
Currency == "EUR" ~ Price * 1,
Currency == "DKK" ~ Price * 0.13,
TRUE ~ NA_real_
)
)
If you have more currencies though or if you will want to track changes in the rates then it will be more effective to keep your prices and rates each in their own data.table and join the rates as needed in order to convert your prices.如果您有更多的货币,或者如果您想要跟踪汇率的变化,那么将您的价格和汇率分别保存在它们自己的 data.table 中并根据需要加入汇率以转换您的价格会更有效。 Something like this:
是这样的:
rates <- tibble::tribble(
~Currency, ~rate,
"CHF", 0.98,
"EUR", 1,
"DKK", 0.13
)
df %>%
left_join(rates, by = "Currency") %>%
mutate(converted = Price * rate) %>%
select(-rate)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.