Given a df
如下,对于每年的实际值和预测值,我需要检查今年的实际值和预测值与上一年的实际值相比是否具有相同的方向:
df <- structure(list(code = c("M0000273", "M0000357", "M0000545"),
name = c("industry", "agriculture", "service"), `2019_actual` = c(16.78,
9.26, 49.38), `2019_pred` = c(17.78, 10.26, NA), `2020_actual` = c(35.74,
NA, 49.38), `2020_pred` = c(36.74, 66.56, 25.36), `2021_actual` = c(30.74,
83.42, 63.26), `2021_pred` = c(31.74, 84.42, 35.23)), class = "data.frame", row.names = c(NA,
-3L))
Out:
code name 2019_actual 2019_pred 2020_actual 2020_pred 2021_actual 2021_pred
1 M0000273 industry 16.78 17.78 35.74 36.74 30.74 31.74
2 M0000357 agriculture 9.26 10.26 NA 66.56 83.42 84.42
3 M0000545 service 49.38 NA 49.38 25.36 63.26 35.23
逻辑是:如果两年的差值为正、负或零,则返回increase
, decrease
and unchanged
分别,如果其中一个或两个值都是NA
s,然后返回NA
.
预期结果:
code name 2019_actual 2019_pred 2020_actual 2020_pred 2021_actual 2021_pred 2020_act_direction 2020_pred_direction 2021_act_direction
1 M0000273 industry 16.78 17.78 35.74 36.74 30.74 31.74 increase increase decrease
2 M0000357 agriculture 9.26 10.26 NA 66.56 83.42 84.42 increase
3 M0000545 service 49.38 NA 49.38 25.36 63.26 35.23 unchanged decrease increase
2021_pred_direction
1 decrease
2
3 decrease
我尝试使用以下代码,但它有两个问题:1.它返回错误:**Error: unexpected ')' in " )"**
; 2.如果我有很多年(即从2010年到2020年),这显然不是获得预期结果的正确方法。
df %>%
mutate(
`2020_act_direction` = case_when(`2020_actual` - `2019_actual` > 0 ~ 'increase',
`2020_actual` - `2019_actual` < 0 ~ 'decrease',
`2020_actual` - `2019_actual` == 0 ~ 'unchanged',
TRUE ~ NA
),
`2020_pred_direction` = case_when(`2020_pred` - `2019_actual` > 0 ~ 'increase',
`2020_pred` - `2019_actual` < 0 ~ 'decrease',
`2020_pred` - `2019_actual` == 0 ~ 'unchanged',
TRUE ~ NA
)
`2021_act_direction` = case_when(`2021_actual` - `2020_actual` > 0 ~ 'increase',
`2021_actual` - `2020_actual` < 0 ~ 'decrease',
`2021_actual` - `2020_actual` == 0 ~ 'unchanged',
TRUE ~ NA
)
`2021_pred_direction` = case_when(`2021_pred` - `2020_actual` > 0 ~ 'increase',
`2021_pred` - `2020_actual` < 0 ~ 'decrease',
`2021_pred` - `2020_actual` == 0 ~ 'unchanged',
TRUE ~ NA
)
)
我该如何处理这个问题?