使用R重新排序数据框和图

时间:2019-03-20 15:01:23

标签: r dataframe dplyr

我正在尝试解决一个简单的问题,但没有找到解决方案。 我有这样的data.frame命令

ID  Description value
Gut-1877    T4_2    574
Gut-1896    T5_2    576
Gut-1466    Donor   544
Gut-1734    T1_2    354
Gut-1720    T0_2    185
Gut-1741    T2_2    173
Gut-1748    T3_2    196
Gut-2431A   T7_2    421
Gut-2125    T6_2    352
Gut-1656    T1_1    258
Gut-1619    T0_1    77
Gut-1323    Relative    351

我想以另一个顺序放置此文件,并且我尝试这样做:

data %>% arrange(value) %>%
  mutate(name = factor(Description, levels=c( "Relative","Donor","T0_1","T1_1","T0_2","T1_2","T2_2","T3_2","T4_2","T5_2","T6_2","T7_2")))

但是后来我不遵守我的订单:

ID  Description value
Gut-1877    T4_2    574
Gut-1896    T5_2    576
Gut-1466    Donor   544
Gut-1734    T1_2    354
Gut-1720    T0_2    185
Gut-1741    T2_2    173
Gut-1748    T3_2    196
Gut-2431A   T7_2    421
Gut-2125    T6_2    352
Gut-1656    T1_1    258
Gut-1619    T0_1    77
Gut-1323    Relative    351

如何按我希望的顺序放置它:

"Relative","Donor","T0_1","T1_1","T0_2","T1_2","T2_2","T3_2","T4_2","T5_2","T6_2","T7_2"

然后如何按照此顺序绘制它们的值? 非常感谢大家,将对您有所帮助。

1 个答案:

答案 0 :(得分:1)

下面是您的代码,但添加了console.log([1,2,3,4,5].slice(1)); // [2, 3, 4, 5] console.log([1,2,3,4,5].slice(2)); // [3, 4, 5] console.log([1,2,3,4,5].slice(3)); // [4, 5] ,以便按arrange对数据框进行排序。

Description

reprex package(v0.2.1)于2019-03-20创建

然后可以像这样绘制数据:

library(dplyr)
library(magrittr)

data <- read.table(text = "ID  Description value
Gut-1877    T4_2    574
           Gut-1896    T5_2    576
           Gut-1466    Donor   544
           Gut-1734    T1_2    354
           Gut-1720    T0_2    185
           Gut-1741    T2_2    173
           Gut-1748    T3_2    196
           Gut-2431A   T7_2    421
           Gut-2125    T6_2    352
           Gut-1656    T1_1    258
           Gut-1619    T0_1    77
           Gut-1323    Relative    351", header = TRUE)

data %<>% arrange(value) %>%
  mutate(Description = factor(Description, levels=c( "Relative","Donor","T0_1","T1_1","T0_2","T1_2","T2_2","T3_2","T4_2","T5_2","T6_2","T7_2"))) %>% 
  arrange(Description)
#>           ID Description value
#> 1   Gut-1323    Relative   351
#> 2   Gut-1466       Donor   544
#> 3   Gut-1619        T0_1    77
#> 4   Gut-1656        T1_1   258
#> 5   Gut-1720        T0_2   185
#> 6   Gut-1734        T1_2   354
#> 7   Gut-1741        T2_2   173
#> 8   Gut-1748        T3_2   196
#> 9   Gut-1877        T4_2   574
#> 10  Gut-1896        T5_2   576
#> 11  Gut-2125        T6_2   352
#> 12 Gut-2431A        T7_2   421

enter image description here