![](/img/trans.png)
[英]R: using ifelse statement to check if column exists, then perform calculation
[英]ifelse statement with calculation in R
我正在尝试编写代码将不同的货币转换为欧元。
当前数据集(df)看起来像这样。
货币 | 价格 |
---|---|
瑞士法郎 | 1000 |
丹麦克朗 | 20000 |
我的目标是改变一列以显示它们有多少欧元。
货币 | 价格 | 欧元 |
---|---|---|
瑞士法郎 | 1000 | 980 |
丹麦克朗 | 20000 | 2600 |
这看起来很容易,但我真的想不通......有人可以帮我吗?
我用 ifelse 尝试了一段代码。
df <- df %>%
mutate(converted = ifelse(Currency == "CHF", Price*0.98,
ifelse(Currency == "EUR", Price*1,
ifelse(Currency == "DKK", Price*0.13))))
它返回此错误消息。
错误:问题与
mutate()
列converted
。 [34mℹ[39mconverted = ifelse(...)
。 [31m✖[39m 非数字参数...
我也试过这个。
df <- df %>%
mutate(converted = if(Currency == "CHF"){
Price*0.98
} else if (Currency == "DKK"){
Price*0.13
} else {
Price*1
}
它返回另一条错误消息。
解析错误(文本= x,srcfile = src):<文本>:9:0:输入7的意外结束:价格* 1 8:} ^
case_when
与嵌套ifelse
正如回复中提到的, 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_
)
)
如果您有更多的货币,或者如果您想要跟踪汇率的变化,那么将您的价格和汇率分别保存在它们自己的 data.table 中并根据需要加入汇率以转换您的价格会更有效。 是这样的:
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.