Here is an example data.table
dt <- data.table(col1 = c(\'A\', \'A\', \'B\', \'C\', \'C\', \'D\'), col2 = c(NA, \'dog\', \'cat\', \'jeep\', \'porsch\', NA))
You missed the parenthesis (maybe a typo), I suppose it should be length(col1) > 1
; And also used ifelse
on a scalar condition which will not work as you expect it to (only the first element from the vector is picked up); If you want to remove NA values from a group when there are non NAs, you can use if/else
:
dt[, .(col2 = if(all(is.na(col2))) NA_character_ else na.omit(col2)), by = col1]
# col1 col2
#1: A dog
#2: B cat
#3: C jeep
#4: C porsch
#5: D NA