如何在 R 中有效地实现合并 [英] How to implement coalesce efficiently in R

查看:70
本文介绍了如何在 R 中有效地实现合并的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

几种 SQL 语言(我主要使用 postgreSQL)有一个名为 coalesce 的函数,它返回每行的第一个非空列元素.当表中有很多 NULL 元素时,这可以非常有效地使用.

Several SQL languages (I mostly use postgreSQL) have a function called coalesce which returns the first non null column element for each row. This can be very efficient to use when tables have a lot of NULL elements in them.

我在 R 的很多场景中也遇到过这种情况,在处理不那么结构化的数据时,其中有很多 NA.

I encounter this in a lot of scenarios in R as well when dealing with not so structured data which has a lot of NA's in them.

我自己做了一个幼稚的实现,但速度太慢了.

I have made a naive implementation myself but it is ridiculously slow.

coalesce <- function(...) {
  apply(cbind(...), 1, function(x) {
          x[which(!is.na(x))[1]]
        })
}

示例

a <- c(1,  2,  NA, 4, NA)
b <- c(NA, NA, NA, 5, 6)
c <- c(7,  8,  NA, 9, 10)
coalesce(a,b,c)
# [1]  1  2 NA  4  6

问题

有没有什么有效的方法可以在 R 中实现 coalesce?

推荐答案

在我的机器上,使用 Reduce 获得了 5 倍的性能提升:

On my machine, using Reduce gets a 5x performance improvement:

coalesce2 <- function(...) {
  Reduce(function(x, y) {
    i <- which(is.na(x))
    x[i] <- y[i]
    x},
  list(...))
}

> microbenchmark(coalesce(a,b,c),coalesce2(a,b,c))
Unit: microseconds
               expr    min       lq   median       uq     max neval
  coalesce(a, b, c) 97.669 100.7950 102.0120 103.0505 243.438   100
 coalesce2(a, b, c) 19.601  21.4055  22.8835  23.8315  45.419   100

这篇关于如何在 R 中有效地实现合并的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆