I'm writing a Shiny app where the user will be inputting data for conditions of their samples, and the script will "automatically" match their inputted conditions to sample names of a given file.
For simplicity, I will not include the shiny code, because I am only struggling with the actual R implementation.
If I already know what the potential conditions are, I could do something like:
library(tidyverse)
x <- data.frame(Samples = c('Low1', 'Low2', 'High1', 'High2',
'Ctrl1', 'Ctrl2'))
x <- x %>% mutate(Conditions = case_when(
str_detect(Samples, fixed("low", ignore_case = T)) ~ "low",
str_detect(Samples, fixed("high", ignore_case = T)) ~ "high",
str_detect(Samples, fixed("ctrl", ignore_case = T)) ~ "ctrl"))
And I would get what I am looking for, a data frame like:
Samples Conditions
Low1 low
Low2 low
High1 high
High2 high
Ctrl1 ctrl
Ctrl2 ctrl
However, I want to loop through a vector of potential conditions and do something like:
library(tidyverse)
condition_options <- c('low', 'high', 'ctrl')
x <- data.frame(Samples = samplenames)
for (j in condition_options) {
x <- x %>% mutate(Condition = case_when(
str_detect(Samples, fixed(j, ignore_case = T)) ~ j))
}
When I do this, the Condition
column is re-written only giving me matches for the last value in the vector. For example:
Samples Conditions
Low1 <NA>
Low2 <NA>
High1 <NA>
High2 <NA>
Ctrl1 ctrl
Ctrl2 ctrl
See Question&Answers more detail:
os