【问题标题】:Rename dataframe columns by spliting its names and melting dataframe afterwards通过拆分其名称并随后熔化数据框来重命名数据框列
【发布时间】:2018-04-12 11:52:53
【问题描述】:

示例数据框:

       col_1  col_2  col_3  col_4
f1     0.1    0.2    0.3    0.4
f2     0.01   0.02   0.03  0.04
f3     0.001  0.002  0.003 0.004

我想重命名列,方法是用sep="_" 拆分列名来得到这个:

       1      2      3      4
f1     0.1    0.2    0.3    0.4
f2     0.01   0.02   0.03   0.04
f3     0.001  0.002  0.003  0.004

然后我想在同一个图上绘制每列(f.name vs f.value)的密度(例如:http://ggplot2.tidyverse.org/reference/geom_freqpoly-11.png)所以我想我需要将它融合成这样的东西:

col   f.name    f.value    
1     f1        0.1
2     f1        0.2
3     f1        0.3
4     f1        0.4
1     f2        0.01
2     f2        0.02
3     f2        0.03
4     f2        0.04
1     f3        0.001
2     f3        0.002
3     f3        0.003
4     f3        0.004

任何建议如何做到这一点?

【问题讨论】:

    标签: r ggplot2 rename


    【解决方案1】:

    不测试代码,使用包'dplyr'和'tidyr'。其中df 是您的输入数据框,以下应该可以工作:

    df %>% gather(col, val, starts_with('col')) %>% 
      separate(col, into=c('nah','col'), sep='_') %>%
      ggplot(aes(x=val, colour=col)) + geom_freqpoly()
    

    【讨论】:

      猜你喜欢
      • 2019-01-10
      • 2018-01-04
      • 2019-08-19
      • 1970-01-01
      • 2021-02-22
      • 1970-01-01
      • 2019-09-26
      • 2022-07-01
      • 2018-05-27
      相关资源
      最近更新 更多