【问题标题】:Dplyr rowwise access entire columnDplyr 按行访问整个列
【发布时间】:2016-05-09 10:00:41
【问题描述】:

给定以下数据

   A B
1  1 2
2  2 2
3  3 3
4  4 4
5  5 4

对于每一行,我想找到 A 首次超过 B 的索引。 所以需要的答案是:

  A B NextIndex
1 1 2         3
2 2 2         3
3 3 3         4
4 4 4         5
5 5 5         5

我对@9​​87654323@ 的处理方法是

A_col<-foo$A  
foo  %>%  rowwise() %>% mutate(NextIndex=which(A_col-B>0)[1] )

我的实际 data.frame 是几百万行,处理时间急剧增加。请注意,我在每行比较中引用了完整的A_col,并且我尝试了使用row_number() 的版本,但没有实现显着的速度提升。 另外,请注意,A 和 B 实际上是我的 data.frame 中的 POSIXct 变量,并且会严格按时间增加,但不会按周期增加。

如何提高这个表达式的效率?

【问题讨论】:

    标签: r dplyr


    【解决方案1】:

    我们可以使用vapply

    foo$nextIndex <- vapply(foo$B, function(x) which(foo$A-x>0)[1], 1)
    foo
    #   A B nextIndex
    #1 1 2         3
    #2 2 2         3
    #3 3 3         4
    #4 4 4         5
    #5 5 4         5
    

    如果值按顺序排列,则另一种选择

    findInterval(foo$B, foo$A)+1L
    #[1] 3 3 4 5 5
    

    dplyr 链中使用它

    foo %>% 
        mutate(rowIndex = findInterval(B, A)+1L)
    

    【讨论】:

      【解决方案2】:

      这个怎么样:

      df$nextIndex <- apply(df, 1, function(x) which.max(df$A - x[2] > 0))
      df
        A B nextIndex
      1 1 2         3
      2 2 2         3
      3 3 3         4
      4 4 4         5
      5 5 4         5
      

      【讨论】:

        猜你喜欢
        • 2018-01-01
        • 2016-07-31
        • 1970-01-01
        • 1970-01-01
        • 2019-03-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-04
        相关资源
        最近更新 更多