my_df <- df %>%
mutate(incExpChange= case_when(
(incNextYear == 'Higher' & INEXQ2 %in% 0:95) ~ INEXQ2,
(incNextYear == 'Lower' & INEXQ2 %in% 0:95) ~ -INEXQ2))
I have two columns 'incNextYear' & 'INEXQ2', I want to convert some positive values in 'INEXQ2' to negative in my new column when incNextYear is 'Lower'. -INEXQ2 is not working for me. What am I doing wrong?
CodePudding user response:
We could use type.convert(as.is = TRUE)
library(dplyr)
df %>%
type.convert(as.is = TRUE) %>%
mutate(incExpChange= case_when(
(incNextYear == 'Higher' & INEXQ2 %in% 0:95) ~ INEXQ2,
(incNextYear == 'Lower' & INEXQ2 %in% 0:95) ~ -INEXQ2))
```
```
rID region incNextYear homeBuying REGION INEXQ1 INEXQ2 V204 incExpChange
<int> <chr> <chr> <chr> <chr> <chr> <int> <chr> <int>
1 1 West Higher BAD West Higher 2 BAD 2
2 2 Northeast Higher BAD Northeast Higher 3 BAD 3
3 3 South Higher BAD South Higher 13 BAD 13
4 4 Midwest Lower BAD Midwest Lower 3 BAD -3
5 5 West Higher BAD West Higher 6 BAD 6
6 6 Midwest Lower BAD Midwest Lower 5 BAD -5
```
CodePudding user response:
Replace
-INEXQ2
with
INEXQ2*(-1)
Replace
(incNextYear == 'Higher' & INEXQ2 %in% 0:95)
with
((incNextYear == 'Higher') && (INEXQ2 %in% 0:95))
another expression is also changed like above.