I a using the following code but it is giving me error
UPDATED_PENALTY['HISTORIC_PENALTY'] <- ave(UPDATED_PENALTY$PENALTY, UPDATED_PENALTY$OFFICIAL_NUMBER, FUN=cumsum)
UPDATED_PENALTY['cum_prodsum']<-NA
UPDATED_PENALTY %>%
mutate(cum_prodsum = ifelse(UPDATED_PENALTY$INSPECTION_CLEARED==TRUE, UPDATED_PENALTY$HISTORIC_PENALTY*0.9, UPDATED_PENALTY$HISTORIC_PENALTY*0.9 UPDATED_PENALTY$PENALTY))
Error
Error in `mutate()`:
! Problem while computing `cum_prodsum = ifelse(...)`.
x `cum_prodsum` must be size 12 or 1, not 32217.
i The error occurred in group 1: OFFICIAL_NUMBER = "XXXXX".
Run `rlang::last_error()` to see where the error occurred.
Also, I want to exclude first "HISTORIC PENALTY" of each "OFFICIAL NUMBER from manipulation and copy the value as it is, rest all apply the above.
CodePudding user response:
We may do
library(dplyr)
UPDATE_PENALTY <- UPDATE_PENALTY %>%
ungroup %>%
mutate(cum_prodsum = case_when(INSPECTION_COUNT == 1
~ HISTORIC_PENALTY,
INSPECTION_CLEARED ~ HISTORIC_PENALTY*0.9,
TRUE ~HISTORIC_PENALTY*0.9 PENALTY))
-output
UPDATE_PENALTY
# A tibble: 46 × 7
OFFICIAL_NUMBER NUM_DEF PENALTY INSPECTION_COUNT INSPECTION_CLEARED HISTORIC_PENALTY cum_prodsum
<chr> <dbl> <dbl> <int> <lgl> <dbl> <dbl>
1 170718 14 60 1 FALSE 60 60
2 803729 0 0 1 TRUE 0 0
3 803729 65 311 2 FALSE 311 591.
4 170718 8 24 2 FALSE 84 99.6
5 170718 0 0 3 TRUE 84 75.6
6 170718 39 110 4 FALSE 194 285.
7 170718 0 0 5 TRUE 194 175.
8 170718 1 5 6 FALSE 199 184.
9 170718 0 0 7 TRUE 199 179.
10 170718 0 0 8 TRUE 199 179.
# … with 36 more rows