如何在for循环中使用mutate()和case_when()? [英] How can I use mutate() and case_when() in a for loop?
问题描述
我正在编写一个Shiny应用程序,用户将在其中输入样品条件的数据,脚本将自动"将其输入条件与给定文件的样品名称匹配.
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.
为简单起见,我将不包含闪亮的代码,因为我仅在实际的R实现中苦苦挣扎.
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))
}
执行此操作时,仅重写Condition
列,使我与向量中的最后一个值匹配.例如:
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
推荐答案
如果使用元编程而不是循环来构建case_when
语句的所有部分,则可能会更容易.试试
This might be easier if you build all parts of your case_when
statement with meta-programming rather than doing a loop. Try
library(tidyverse)
condition_options <- c('low', 'high', 'ctrl')
conditions <- purrr::map(condition_options,
~quo(str_detect(Samples, fixed(!!.x, ignore_case = T))~!!.x))
x <- data.frame(Samples = samplenames)
x %>% mutate(Condition = case_when(!!!conditions) )
# Samples Condition
# 1 Low1 low
# 2 Low2 low
# 3 High1 high
# 4 High2 high
# 5 Ctrl1 ctrl
# 6 Ctrl2 ctrl
在这里map
构建您希望在case_when
语句中拥有的所有不同公式.然后,我们使用!!!
将其插入mutate
表达式中.
Here the map
build all the different formulas you would expect to have in the case_when
statement. Then we use !!!
to insert them into the mutate
expression.
这篇关于如何在for循环中使用mutate()和case_when()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!