Is there a way to retrieve the vectors selected by fcoalesce?

Viewed 40

When using fcoalesce, is there any way I can retrieve the indices or names of the selected vectors?

Here is a simplified two-vector example, for the following coalesce of vectors a and b:

library(data.table)
a = c(NA,2,3,4,NA)
b = c(1,3,3,4,5)
fcoalesce(a,b)
 
[1] 1 2 3 4 5

I'd like to see something like this:

b,a,a,a,b

A real life example could have any number of vectors.

2 Answers

We can use ifelse - coalesce is simply taking the first non-NA for each row/element between two vectors/columns. Thus, create a logical condition for NA elements, and specify the 'yes', 'no' as the object names

ifelse(is.na(a), 'b', 'a')
[1] "b" "a" "a" "a" "b"

I managed to solve it by merging all vectors into a data.table (dt_combined) and coalescing them iteratively:

apply(dt_combined, 1, function(i){
  (1:length(dt_combined))[ which(!is.na(i))[1] ]
})

One could also get the column names instead of the column index:

apply(dt_combined, 1, function(i){
  colnames(dt_combined)[ which(!is.na(i))[1] ]
})
Related