【问题标题】:Adding column indicating the number of times its corresponding value occurs in another column添加列表示其对应值在另一列中出现的次数
【发布时间】:2018-03-31 13:15:15
【问题描述】:

我的数据集已附上。我想创建一个新列,其中包含每个唯一季度 (QUART) 标识符的长度。换句话说,对于每一行,我想创建一个新值,其对应的 QUART 出现在数据集中的次数

所以第 1 行应该有一个值为“4”的新列,因为 1992.2 出现了 4 次。

我的数据结构看起来像“

ID   QUART      Trasaction   New Column (I want)
1     1992.2     Company 1         4
2     1992.2     Company 2         4 
3     1992.2     Company 3         4 
4     1992.2     Company 4         4
5     1992.3     Company 5         1
6     1992.4     Company 6         1
7     1993.1     Company 7         1

谢谢

enter image description here

【问题讨论】:

    标签: r dplyr


    【解决方案1】:

    您可以使用dplyr::group_byn() 来计算每个QUART 的相同条目数:

    library(tidyverse);
    df %>%
        group_by(QUART) %>%
        mutate(count = n());
    ## A tibble: 7 x 4
    ## Groups:   QUART [4]
    #     ID QUART Trasaction count
    #  <int> <dbl> <fct>      <int>
    #1     1 1992. Company 1      4
    #2     2 1992. Company 2      4
    #3     3 1992. Company 3      4
    #4     4 1992. Company 4      4
    #5     5 1992. Company 5      1
    #6     6 1992. Company 6      1
    #7     7 1993. Company 7      1
    

    样本数据

    df <- read.table(text =
        "ID   QUART      Trasaction
    1     1992.2     'Company 1'
    2     1992.2     'Company 2'
    3     1992.2     'Company 3'
    4     1992.2     'Company 4'
    5     1992.3     'Company 5'
    6     1992.4     'Company 6'
    7     1993.1     'Company 7'", header = T)
    

    【讨论】:

    • 我喜欢基本的 R 解决方案 @MKR!非常简洁:-)
    • 谢谢!!我虽然因为值是double,因此一种比较单个值的方法将提供更多控制,因为人们甚至可以在double.eps的范围内进行比较
    【解决方案2】:

    base-R 中的一个选项可以使用mapply 来实现:

    df$count <- mapply(function(x)sum(df$QUART == x), df$QUART)
    #    ID  QUART Trasaction count
    # 1  1 1992.2  Company 1     4
    # 2  2 1992.2  Company 2     4
    # 3  3 1992.2  Company 3     4
    # 4  4 1992.2  Company 4     4
    # 5  5 1992.3  Company 5     1
    # 6  6 1992.4  Company 6     1
    # 7  7 1993.1  Company 7     1
    

    注意:因为QUART 的类型是numeric / double。因此,我的建议是将两个值的差异与double precision 硬件限制进行比较,而不是与== 进行比较。为了解决这些情况,解决方案可能是

    mapply(function(x)sum(abs(df$QUART - x) <= 0.000001), df$QUART)
    

    数据

    df <- read.table(text = "
    ID   QUART      Trasaction   
    1     1992.2     'Company 1'   
    2     1992.2     'Company 2'   
    3     1992.2     'Company 3'   
    4     1992.2     'Company 4'   
    5     1992.3     'Company 5'   
    6     1992.4     'Company 6'   
    7     1993.1     'Company 7'",
    header = TRUE, stringsAsFactors = FALSE)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-26
      • 2015-04-29
      • 2022-06-16
      • 2016-09-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多