Organising factor based on two variables in R using fct_reorder2() from forcats package

233 Views Asked by At

From the table below, I would like to organise the factor levels of lineage based on the IDs in the two other columns. These IDs represent the ordered medians of two different variables I would like to sort by.

Example data:

# A tibble: 42 x 4
   lineage    lineage_sub_subtype      id_lss  id_l
   <chr>      <fct>                     <int> <int>
 1 lymphocyte b_cell_mediastinal_large      3    23
 2 lymphocyte b_cell_mantle_cell           17    23
 3 lymphocyte b_cell_mantle_cell           17    23
 4 lymphocyte b_cell_burkitt               21    23
 5 lymphocyte b_cell_burkitt               21    23
 6 lymphocyte b_cell_burkitt               21    23

I have tried to organise the factor levels by using fct_reorder2(). This organises the lineage_sub_subtype by id_l but does not order these by id_lss.

plt_data = data %>%
  mutate(lineage_sub_subtype = fct_reorder2(.f = lineage_sub_subtype, 
                               id_lss, 
                               id_l,
                               .desc = F))

Using this code, "b_cell_burkitt" comes before "b_cell_mediastinal_large" in my factor levels.

Am I misusing fct_reorder2()? How can I achieve what organising by my factor levels by two variables.

I am currently plotting something like this (excerpt from larger graph) but would like to have each group (lineage) organised in descending median order.

Thanks for your help in advance!

0

There are 0 best solutions below