Insert a blank row after each group of data

前端 未结 2 2055
刺人心
刺人心 2020-11-30 12:57

This question has been asked for excel. How to automatically insert a blank row after a group of data

I would like to know if there is a function for doing the same

相关标签:
2条回答
  • 2020-11-30 13:22

    First transform all columns to character vectors:

    df_new <- as.data.frame(lapply(df, as.character), stringsAsFactors = FALSE)
    

    Then you can create the output you're looking for:

    head(do.call(rbind, by(df_new, df$group, rbind, "")), -1 )
    
    #      group xvalue yvalue
    # a.1      a     16      1
    # a.2                     
    # b.2      b     17      2
    # b.3      b     18      3
    # b.31                    
    # c.4      c     19      4
    # c.5      c     20      5
    # c.6      c     21      6
    # c.41                    
    # d.7      d     22      7
    # d.8      d     23      8
    # d.9      d     24      9
    # d.10     d     25     10
    
    0 讨论(0)
  • 2020-11-30 13:34

    Sven has answered exactly what you've asked for, but I think what you want to do is a generally bad idea.

    If visual separation is all that you are hoping to achieve, I would recommend just using split:

    split(df, df$group)
    # $a
    #   group xvalue yvalue
    # 1     a     16      1
    #
    # $b
    #   group xvalue yvalue
    # 2     b     17      2
    # 3     b     18      3
    #
    # $c
    #   group xvalue yvalue
    # 4     c     19      4
    # 5     c     20      5
    # 6     c     21      6
    #
    # $d
    #    group xvalue yvalue
    # 7      d     22      7
    # 8      d     23      8
    # 9      d     24      9
    # 10     d     25     10
    

    This has the advantages of (1) visual separation, (2) easy indexing, (3) no conversion of your data, and (4) allowing you to run the same functions on different subsets of your data.

    0 讨论(0)
提交回复
热议问题