【问题标题】:dplyr if else statementdplyr if else 语句
【发布时间】:2020-10-08 16:37:04
【问题描述】:

我正在尝试根据降水类型(雪、雨、混合)编写 if else 语句。当降水为雪或混合时,我需要使用基于风速的校正(即降水的校正因子),但如果是雨,则不需要应用校正因子。

这是我尝试为此编写的代码:

  mutate(Precip_Corr = ifelse(
    PrecipType == "Snow", exp(-0.04*Wind_ms^1.75),
    PrecipType == "Mixed", 1.0104-(0.0562*Wind_ms)),
    Precip_Type == "Rain", Precip_mm)

这是df:

            date.time Air.Temp_F DewPtTemp_F  RH_. WindDir_DegfromN WindSp_knots HourlyPrecip_in HourlyPrecipT.in Precip_mm precip_cum_mm
1 2019-09-01 00:55:00       55.9          52 86.71                0            0               0            0.000     0.000         0.000
2 2019-09-01 01:55:00       61.0          54 77.72              310            3               T            0.005     0.127         0.127
3 2019-09-01 02:55:00       60.1          54 80.25                0            0               0            0.000     0.000         0.127
4 2019-09-01 03:55:00       57.9          54 86.82              170            5               0            0.000     0.000         0.127
5 2019-09-01 04:55:00       57.0        53.1 86.77                0            0               0            0.000     0.000         0.127
6 2019-09-01 05:33:00       57.9          54 86.82              260            4               0            0.000     0.000         0.127
  AirTemp_C PrecipType  Wind_ms
1  13.27778       Rain 0.000000
2  16.11111       Rain 1.543210
3  15.61111       Rain 0.000000
4  14.38889       Rain 2.572016
5  13.88889       Rain 0.000000
6  14.38889       Rain 2.057613

这是我得到的错误:

Error: Problem with `mutate()` input `Precip_Corr`.
x unused argument (1.0104 - (0.0562 * Wind_ms))
i Input `Precip_Corr` is `ifelse(...)`.

【问题讨论】:

  • 您可以在您的 df 上使用 dput() 并将其发布在此处为我们创建一个最小的工作示例吗?

标签: r if-statement dplyr


【解决方案1】:

你上面的代码有两个错误:

  1. 括号放错地方了
  2. 当您检查多个条件时,您可能需要case_when 而不是ifelse

正如您所写的那样,您的ifelse 语句在错误的位置有一个括号:

  mutate(Precip_Corr = ifelse(
    PrecipType == "Snow", exp(-0.04*Wind_ms^1.75),
    PrecipType == "Mixed", 1.0104-(0.0562*Wind_ms)), # this bracket closes the ifelse statement
    Precip_Type == "Rain", Precip_mm) # these are in the mutate, not the ifelse

将其更正为:

  mutate(Precip_Corr = ifelse(
    PrecipType == "Snow", exp(-0.04*Wind_ms^1.75),
    PrecipType == "Mixed", 1.0104-(0.0562*Wind_ms), # remove excess bracket
    Precip_Type == "Rain", Precip_mm)) # add moved bracket

但是,在这次更正之后,ifelse 的参数太多了:

  • ifelse 采用如下 3 个参数:ifelse(condition, value_if_yes, value_if_no)
  • 你可能想要case_when,它接受任意数量的条件case_when(condition1 ~ value1, condition2 ~ value2, ... )

所以你可能需要的代码是:

  mutate(Precip_Corr = case_when(
    PrecipType == "Snow" ~ exp(-0.04*Wind_ms^1.75),
    PrecipType == "Mixed" ~ 1.0104-(0.0562*Wind_ms),
    Precip_Type == "Rain" ~ Precip_mm))

注意在条件和它们的值之间使用~而不是逗号。

【讨论】:

    猜你喜欢
    • 2019-04-09
    • 1970-01-01
    • 2017-02-05
    • 2015-07-06
    • 2012-08-05
    • 1970-01-01
    • 2021-09-11
    • 1970-01-01
    相关资源
    最近更新 更多