How to implement coalesce efficiently in R

From data.table >= 1.12.3 you can use fcoalesce.

library(data.table)
fcoalesce(a, b, c)
# [1]  1  2 NA  4  6

fcoalesce can also take “a single plain list, data.table or data.frame”. Thus, if the vectors above were columns in a data.frame (or a data.table), we could simply supply the name of the data set:

d = data.frame(a, b, c)
# or d = data.table(a, b, c) 
fcoalesce(d)
# [1]  1  2 NA  4  6

For more info, including a benchmark, see NEWS item #18 for development version 1.12.3.

Leave a Comment