【问题标题】:How to count occurrences of sequences of values in a data frame?如何计算数据框中值序列的出现次数?
【发布时间】:2018-07-05 18:39:52
【问题描述】:

我有一个数据框,其中有一列值(随机分配的处理)1、2、3。类似于:

一、治疗 1,1 2,3 3,2 4,2 5,1 6,3 7,3 8,2 9,1 ...

数据框中的每个 3 行块包含三个可用值的排列,例如对于(1,3,2)上方的第1-3行,对于第4-6行(2,1,3),对于第7-9行(3,2,1)等。数据框中的行数可以被3整除。

我需要计算排列的出现次数 - 我该怎么做?

【问题讨论】:

  • 您是要计算itreatment 的排列数还是只计算treatment?如果只有treatment,您是否正在尝试计算每组 3 行的排列数?
  • 我想要每 3 行发生的处理排列的计数。每个治疗块只能分配一次。

标签: r count sequence permutation


【解决方案1】:

在下文中,treatment 是数据框中的那一列(其长度是 3 的倍数)。只需使用您的示例数据,就有treatment <- c(1, 3, 2, 2, 1, 3, 3, 2, 1)。那么

M <- matrix(treatment, ncol = 3, byrow = TRUE)
radix <- 10 ^ (2:0)
ID <- M %*% radix
table(ID)

#132 213 321 
#  1   1   1 

也许更易于使用的版本是使用paste0 为排列索引生成IDID &lt;- apply(M, 1L, paste0, collapse = ""),但这比我在上面使用的矩阵向量乘法的效率要低得多@987654327 @向量。

【讨论】:

    【解决方案2】:

    使用count的基于dplyr的解决方案可以是:

    library(dplyr)
    
    # Group of every 3 rows
    df %>% group_by(grp = (row_number()-1)%/%3) %>%
      #use paste with argument 'collapse' to find distinct permutations. 
      summarise(Permutation = paste(treatment, collapse=",")) %>%
      count(Permutation)
    
    # # A tibble: 3 x 2
    #   Permutation     n
    #   <chr>       <int>
    # 1 1,3,2           1
    # 2 2,1,3           1
    # 3 3,2,1           1
    

    数据:

    df <- read.table(text=
    "i,treatment
    1,1
    2,3
    3,2
    4,2
    5,1
    6,3
    7,3
    8,2
    9,1",
    header = TRUE, sep=",")
    

    【讨论】:

    • 这也正是我想要的。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2019-08-14
    • 1970-01-01
    • 1970-01-01
    • 2021-02-22
    • 2019-04-24
    • 2015-09-09
    • 1970-01-01
    • 2022-01-04
    相关资源
    最近更新 更多