【问题标题】:a speedy way to compare two rows比较两行的快速方法
【发布时间】:2019-07-03 12:25:54
【问题描述】:

我有一个包含 2 行和 30406 列的大型数据框。我需要计算给定列的两行中出现 0 的次数(匹配),以及在给定的列中出现 0 的次数而不出现在另一行中的次数(不匹配)。

我认为如果我只是遍历所有内容并比较每一列,考虑到有 >30k 列,这将花费太长时间

head(to_compare)[1:5]
     bin:82154:182154 bin:82154:282154 bin:82154:382154 
bin:82154:482154
1-D1.txt                0                1                2                
0
1-D2.txt                1                1                1                
1
     bin:82154:582154
1-D1.txt                0
1-D2.txt                0

输出

match
1

no_match
1

【问题讨论】:

  • 你好,当两者都不是0时你会怎么做?忽略那些列?
  • 完全正确

标签: r dataframe compare match


【解决方案1】:

您可以将colSums 用于矢量化解决方案:

set.seed(123)
df <- as.data.frame(matrix(round(runif(50, 0, 2)), nrow = 2))

# Match 
sum(colSums(df==0) == 2)
[1] 2

# No match
sum(colSums(df==0) == 1)
[1] 8

【讨论】:

    【解决方案2】:
    set.seed(123)
    df <- as.data.frame(matrix(round(runif(10, 0, 2)), nrow = 2))
    
    # Count the number of 0 for each column
    sum(apply(df, 2, function(x) all(x == 0))) # Match
    
    # Count the number of 0 is present in one row and not in another for each column
    sum(apply(df, 2, function(x) any(x == 0) & (x[1] != x[2]))) # No match
    

    【讨论】:

    • 因此,如果我想用 1 而不是 0 来执行此操作,则不匹配将是: sum(apply(to_compare, 2, function(x) any(x == 1) & (x[0 ] != x[2])))
    • 没错。在此逻辑中,您将查看两行中的任何数字是否为 ONE,或者您选择的另一个数字,然后比较它们是否不同。
    【解决方案3】:

    另一种非常简单的方法是首先将列切换为行,然后使用rowSums

    #Create sample df
    df <- data.frame(col1 = c(0,1), col2 = c(1,0), col3 = c(1,1), col4 = c(0,2), col5 = c(3,0), col6 = c(0,0))
    
    #Convert columns to rows
    df_long <- t(df)
    
    #Count number of 0s in every row and show in table of 0, 1 or 2 zeros
    table(rowSums(df_long == 0))
    
    0 1 2 
    1 4 1 
    

    【讨论】:

    • 或者只是表(colSums(df != 0))
    • 确实!非常好!
    【解决方案4】:
    set.seed(7)
    n <- 30406
    to_compare <- data.frame(matrix(floor(runif(n*2, 0, 3)), nrow = 2))
    
    table(colSums(to_compare==0))
    #    0     1     2 
    #13519 13513  3374 
    #
    #0..no zero in column (13519)
    #1..one row in column has a zero (13513)
    #2..both rows in column are zero (3374)
    
    system.time(table(colSums(to_compare==0)))
    #       User      System verstrichen 
    #      0.332       0.000       0.330 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-13
      • 1970-01-01
      • 2019-03-07
      • 1970-01-01
      相关资源
      最近更新 更多