【问题标题】:is there an easy way to make dataframes look nice?有没有一种简单的方法可以让数据框看起来不错?
【发布时间】:2020-01-25 20:40:48
【问题描述】:

我有一个数据框,它的结构对于某些用途来说很好,但绝对不适合 GGPLOT。有没有改造的功能

x <- data.frame(head_1 = c(1,2,3,1,2,3),
           head_2 = c(4,5,6,1,2,3),
            date = c("01-01-2019","01-01-2019","01-01-2019","02-01-2019","02-01-2019","02-01-2019"))

进入

y <- data.frame(type= c("head_1","head_1","head_1","head_1","head_1","head_1",
                    "head_2","head_2","head_2","head_2","head_2","head_2"),
            date = c("01-01-2019", "01-01-2019","01-01-2019","01-01-2019","01-01-2019","01-01-2019",
                     "02-01-2019", "02-01-2019","02-01-2019","02-01-2019","02-01-2019","02-01-2019"),
            value= c(1,2,3,1,2,3,4,5,6,1,2,3 ))

【问题讨论】:

    标签: r function tidyr


    【解决方案1】:

    使用tidyr包修订版>1.0中新增的pivot_longer函数可以在一行中进行转换。

    library(tidyr)
    y<-pivot_longer(x, cols = starts_with("head"), names_to = "type", values_to = "value")
    
    y
    
     A tibble: 12 x 3
       date       type   value
       <fct>      <chr>  <dbl>
     1 01-01-2019 head_1     1
     2 01-01-2019 head_2     4
     3 01-01-2019 head_1     2
     4 01-01-2019 head_2     5
     5 01-01-2019 head_1     3
     6 01-01-2019 head_2     6
     7 02-01-2019 head_1     1
     8 02-01-2019 head_2     1
     9 02-01-2019 head_1     2
    10 02-01-2019 head_2     2
    11 02-01-2019 head_1     3
    12 02-01-2019 head_2     3
    

    【讨论】:

    • 好奇的@DaveT, gather() 也能解决问题,只是时间更长?
    • 是的,gather 也可以,但是 tidyr 包的未来方向是从 gather/separate 转移到 pivot_widerpivot_longer。新的枢轴函数比旧版本的功能更强大。
    • 老板发话了
    • @DaveT 我有一个问题,我个人会简单地使用 data.table 中的melt()。有什么理由我应该使用那些pivot() 函数吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-03
    • 2011-08-31
    • 1970-01-01
    • 2012-07-26
    • 2020-10-18
    • 1970-01-01
    • 2012-09-15
    相关资源
    最近更新 更多