modify values of some values in tibble based on multiple conditions

--Hi all,

i try to change some values in tibble based on conditions from lists such as:

filter(data,sample==tib_outliers$sample & target==tib_outliers$target) %>% mutate(concent=0,PoissonConfMax=0,PoissonConfMin=0)

tib_outliers is a dataframe with columns samples and target, i use those 2 columns as conditions in filter command.

data is the target tibble in which i need the values, the command works fine but it returns only the rows on which the filter is applied.
I need also to return the others rows not affected by the filter, how to do that ?

thank you --

It may not be very elegant (or "tidy"), but you can try the following. (I'm assuming that you want the modified data in a separate tibble, which I'm calling result.)

ix <- which(data$sample==tib_outliers$sample & data$target==tib_outliers$target)
result <- data
result[ix, "concent"] <- 0
result[ix, "PoissonConfMax"] <- 0
result[ix, "PoissonConfMin"] <- 0

not elegant but it works, that's the goal

I think what you want, at least if you want to keep the mutate, is something like this:

df _new <- data %>% mutate(
across(c(concert, PoissonConfMax, PoissonConfMin),
~ if_else( sample==tib_outliers$sample & target==tib_outliers$target , 0, .x) )
)

That should keep all rows and update the ones that match the test to 0 and the ones that don't keep the same value, the .x
This works if all values will be set the same, ie. 0 If you need to set to different values you will need an if_else for each variable or a case_when with entries for each variable.

1 Like