LeGeniusII
LeGeniusII

Reputation: 960

R data.table merge two columns from the same table

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

Answers (2)

dc37
dc37

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

Uwe
Uwe

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

Related Questions