Zach Fara
Zach Fara

Reputation: 101

How to combine columns into one column ignoring NAs (data.table)

I have a data.table like below. I want to merge two columns A and B into one but excluding the missing values (if exists)

dt <- data.table("title"=c("A", "B", NA, "D"), 
             "sha"=c("1", NA, "3", NA),
             "date" = c("1/1/2020","1/2/2020","1/3/2020","1/4/2020$"))

the result for the new column should be like

new
A1
B
3
D

I want to implement it in data.table. looking for something like dplyr::coalesce

Upvotes: 0

Views: 833

Answers (1)

akrun
akrun

Reputation: 886948

With two columns, we may either use fifelse or create a column with the 'title' and then use indexing in i based on non-NA elements to paste

library(data.table)
dt[, new := title][!is.na(sha), new := paste0(new, sha)]

If there are multiple columns, one option is also with unite with na.rm = TRUE to remove the NA elements

library(tidyr)
dt[, unite(.SD, new, title, sha, na.rm = TRUE, sep = "", remove = FALSE)]

Or use do.call with paste after replacing the NA with ""

nm1 <- c('title', 'sha')
dt[, new := do.call(paste, c(lapply(.SD, \(x)
     replace(x, is.na(x), "")), sep="")),.SDcols = nm1]

Upvotes: 2

Related Questions