# Help with For and mutate

Hello to everyone, this is my first post. I used to be an average+ SAS programmer (I'm still do). I am only one week old with R. Maybe this question sound elemental for you, bit for me...

I wrote this code:

library(rlang)
regi <- c(1,2,3,4,5,6)
vQUINT <- list(parse_expr("quintilH1"), parse_expr("quintilH2"), parse_expr("quintilH3"), parse_expr("quintilH4"), parse_expr("quintilH5"), parse_expr("quintilH6"))

q1H <- quintilesH\$H_20
q2H <- quintilesH\$H_40
q3H <- quintilesH\$H_60
q4H <- quintilesH\$H_80

#REGIONES
quintilH_AUX <- subset(persona, vFINHOG==1 & ingtotp_P>0) %>%
select (nprvnc, nups, narea, nordn, nvvnd, nhogar, ingtotp_P, expan, region, vFINHOG)
for (i in regi){
quintilH_AUX <- quintilH_AUX %>%
mutate(vQUINT[i]=case_when(region==i & ingtotp_P <= q1H [i+1] ~1)) %>%
mutate(vQUINT[i]=case_when(region==i & ingtotp_P > q1H [i+1] & ingtotp_P <= q2H [i+1] ~2, TRUE ~ vQUINT[i])) %>%
mutate(vQUINT[i]=case_when(region==i & ingtotp_P > q2H [i+1] & ingtotp_P <= q3H [i+1] ~3, TRUE ~ vQUINT[i])) %>%
mutate(vQUINT[i]=case_when(region==i & ingtotp_P > q3H [i+1] & ingtotp_P <= q4H [i+1] ~4, TRUE ~ vQUINT[i])) %>%
mutate(vQUINT[i]=case_when(region==i & ingtotp_P > q4H [i+1] ~5, TRUE ~ i))
}

I cant make this loop works. The only problem I found is when i try to create a column with mutate using iteration.

Welcome to the community!

I think you may be overcomplicating a little bit. What you shared is not replicable, as we don't know what is `quintilesH`. But what I understand from the rest of the code is that you're not using `case_when` correctly.

You are supposed to use `case_when` in this format:

``````case_when(condition_1 ~ expected_result_in_condition_1,
condition_2 ~ expected_result_in_condition_2,
...,
condition_n ~ expected_result_in_condition_n,
TRUE ~ expected_result_when_all_other_condition_fail)
``````

Don't use each condition in a different call. And also for this specific use, check the `cut` and `findInterval` functions.

If you face any problem, please provide more details in for of a reproducible example (reprex). If you are unfamiliar with what that is, check this FAQ.

And, you're using `rlang` in your first week of R journey!! I'm using it for almost 5 years, and I know I have never used deep `tidyverse` stuff. Little bit of common `dplyr` and `purrr` is enough for what I do, though I must admit I don't really use R much other than statistics assignments.

1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.