Filter from a variable using a loop

Hi there,

I want to filter out one condition at a time from the "condition" variable, in order of the vec_cond vector (i.e. remove Hypertension first and then run code, then remove ActiveAsthma as well... down until no conditions are left) and run the two lines of code below each time. In my real code I make tables and run a regression each time, but for simplicity I have just kept in two lines here.

df <- df %>%
pivot_wider(names_from = condition, values_from = Age)

I think this should be possible within a loop.

Here is the vector and df:

vec_cond = c(Hypertension, ActiveAsthma, Diabetes, Eczema, AnyCancer_Last5Yrs, Hayfever)

df <- tibble::tribble(
~UniquePatientID, ~Age, ~condition,
1, 43, "Hypertension",
1, 43, "Diabetes",
2, 52, "Hypertension",
2, 52, "ActiveAsthma",
2, 52 "CHD",
2 52, "Eczema",
3, 18, "Hayfever",
4, 67, "Eczema",
5, 78, "Hypertension",
5, 78, "AnyCancer_Last5Yrs"

Would it be something like:

for(i in vec_cond){
df <- df %>%
filter(condition != i) %>%
pivot_wider(names_from = condition, values_from = Age)

Many thanks for your help

I think you want

for(i in seq_along(vec_cond)){
      tmp <- df %>%
        filter(!condition %in% vec_cond[1:i]) %>%
        pivot_wider(names_from = condition, values_from = Age)

This is fantastic, exactly what I needed, thank you so much!

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

If you have a query related to it or one of the replies, start a new topic and refer back with a link.