【问题标题】:R - Combining rows and renaming valuesR - 组合行和重命名值
【发布时间】:2017-09-28 13:13:33
【问题描述】:

我正在尝试在重新编码以下数据框中的值时合并行:

     Days    Object   Frequency
1    1       Fruit    20
2    2       Fruit    21
3    3       Fruit    41
4    4       Fruit    12
5    5       Fruit    1   
6    6       Fruit    9
8    8       Fruit    1
9    9       Fruit    14

基本上,我想将这些天分组为如下的分类变量:

    Days    Object    Frequency
1   1-2     Fruit     41
2   3-4     Fruit     43
3   5+      Fruit     25

在为 Days 列创建新值时有什么方法可以合并?

抱歉,如果这是一个愚蠢的问题

【问题讨论】:

    标签: r dataframe merge dplyr


    【解决方案1】:

    在基础 R 中,您可以组合 cutaggregate。在这里,cut 生成日组,并为这些组提供标签。这在一个带有 Object to aggregate 的列表中提供,以执行完整的分组。 aggregate 将频率作为其第一个参数并应用 sum

    aggregate(dat$Frequency, list(Days=cut(dat$Days, c(-Inf, 2, 4, Inf),
                                           labels=c("1-2", "2-4", "5+")),
                                  object=dat$Object),
              sum)
    

    返回

      Days object  x
    1  1-2  Fruit 41
    2  2-4  Fruit 53
    3   5+  Fruit 25
    

    要重命名 x 变量,您可以将其包装在 setNames 中,或者在第二行中使用 names<-

    与此等效的data.table

    library(data.table)
    setDT(dat)[, sum(Frequency),
               by=list(Days=cut(dat$Days, c(-Inf, 2, 4, Inf), labels=c("1-2", "2-4", "5+")),
                       object=dat$Object)]
       Days object V1
    1:  1-2  Fruit 41
    2:  2-4  Fruit 53
    3:   5+  Fruit 25
    

    【讨论】:

      【解决方案2】:

      您可以在group_by 中动态创建组变量,然后进行汇总(假设您也想按Object 进行分组):

      df %>% 
          group_by(Days = if_else(Days %in% c(1,2), "1-2", if_else(Days %in% c(3,4), "3-4", "5+")), 
                   Object) %>% 
          summarise(Frequency = sum(Frequency))
      
      # A tibble: 3 x 3
      # Groups:   Days [?]
      #   Days Object Frequency
      #  <chr> <fctr>     <int>
      #1   1-2  Fruit        41
      #2   3-4  Fruit        53
      #3    5+  Fruit        25
      

      【讨论】:

        猜你喜欢
        • 2010-12-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-10-10
        • 1970-01-01
        • 2021-08-26
        • 2020-01-20
        • 1970-01-01
        相关资源
        最近更新 更多