Reputation: 960
I have:
inputDT <- data.table(COL1 = c(1, NA, NA), COL1 = c(NA, 2, NA), COL1 = c(NA, NA, 3))
inputDT
COL1 COL1 COL1
1: 1 NA NA
2: NA 2 NA
3: NA NA 3
I want
outputDT <- data.table(COL1 = c(1,2,3))
outputDT
COL1
1: 1
2: 2
3: 3
Essentially, I have a data.table with multiple columns whose names are the same (values are mutually exclusive), and I need to generate just one column to combine those.
How to achieve it?
Upvotes: 1
Views: 299
Reputation: 16178
Alternatively (less elegant than @Uwe's answer), if you have only numbers and NA
, you can calculate the max of each row while removing NA:
library(data.table)
inputDT[, .(COL2 = do.call(pmax, c(na.rm=TRUE, .SD)))]
COL2
1: 1
2: 2
3: 3
Upvotes: 1
Reputation: 42544
The OP is asking for a data.table
solution. As of version v1.12.4 (03 Oct 2019), the fcoalesce()
function is available:
library(data.table)
inputDT[, .(COL1 = fcoalesce(.SD))]
COL1 1: 1 2: 2 3: 3
Upvotes: 7