【发布时间】:2020-01-11 15:16:28
【问题描述】:
我正在编写一个闪亮的应用程序,用户将在其中输入样本条件的数据,脚本将“自动”将他们输入的条件与给定文件的样本名称相匹配。
为简单起见,我不会包含闪亮的代码,因为我只是在为实际的 R 实现而苦苦挣扎。
如果我已经知道潜在的条件是什么,我可以这样做:
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"))
我会得到我正在寻找的数据框,例如:
Samples Conditions
Low1 low
Low2 low
High1 high
High2 high
Ctrl1 ctrl
Ctrl2 ctrl
但是,我想遍历潜在条件向量并执行以下操作:
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 列被重写,只给我匹配向量中的最后一个值。例如:
Samples Conditions
Low1 <NA>
Low2 <NA>
High1 <NA>
High2 <NA>
Ctrl1 ctrl
Ctrl2 ctrl
【问题讨论】: