如何在选定的列上排列数据框,同时在顶部保留两个特定的行?

How to arrange a dataframe on a chosen column, while keeping two specific rows at the top?

我有一个 table 有很多样本。我想在 table 的顶部设置正负控件,但需要帮助找出最直接的方法来执行此操作。

这是一个最小的示例数据框:

df = data.frame(structure(list(Well = c("A1", "A2", "B1", "B2"), 
                               Sample = c("Asample 2", "Positive control", "Asample 1", "Negative control"))))

任务:

期望的输出:

  well  sample          
  <chr> <chr>           
1 A2    Positive control
2 B2    Negative control
3 A1    Asample 2       
4 B1    Asample 1  

一个解决方案是使用 well 级别将 sample 设为 factor(),然后适当地重新级别 sample

df %>% 
    arrange(Well) %>% 
    mutate(
        Sample = fct_relevel(
            fct_inorder(factor(Sample)), 
            c('Positive control', 'Negative control')
        )
    ) %>% 
    arrange(Sample)
  Well           Sample
1   A2 Positive control
2   B2 Negative control
3   A1        Asample 2
4   B1        Asample 1

另一个解决方案:

df %>% arrange(match(Sample,c("Positive control", "Negative control")),Well)

  Well           Sample
1   A2 Positive control
2   B2 Negative control
3   A1        Asample 1
4   B1        Asample 2