1
DATA = data.frame(x1=c("dog","cat","fox","mouse",NA,NA),
x2=c("dog","cat","rhino", NA, "cat","fox"),
x3=c("dog","cat",NA,NA,"cat","fox"),
WANT=c("dog","cat","fox","mouse","cat","fox"))

I have 'DATA' with x1, x2, x3 and I wish to collapse x1, x2, x3 into 'WANT' which just takes the first reported value starting from x1, using data.table

bvowe
  • 3,004
  • 3
  • 16
  • 33
  • 2
    See linked post, this should work using data.table: `DATA[, WANT := fcoalesce(x1, x2, x3) ]` – zx8754 Feb 01 '21 at 15:17
  • 1
    Notable in that dupe question is [this answer](https://stackoverflow.com/a/56768679/3358272) that demonstrates `data.table::fcoalesce`. I say that based on you including the [tag:data.table] tag, even if the question itself does not produce a `data.table` object. – r2evans Feb 01 '21 at 15:18
  • @zx8754 is it possible to instead of saying 'x1, x2, x3' store the column names into a vector and then place fcoalesce(VECTOR) ? – bvowe Feb 01 '21 at 15:23
  • 1
    Something like this? `cc <- c("x1", "x2", "x3"); DATA$WANT <- fcoalesce(DATA[, cc])` – zx8754 Feb 01 '21 at 15:33
  • Better data.table way of doing would be: `cc <- c("x1", "x2", "x3"); DATA[, WANT := do.call(fcoalesce, .SD), .SDcols = cc ]`. See related [GitHub issue: 4885](https://github.com/Rdatatable/data.table/issues/4885) – zx8754 Feb 01 '21 at 21:01

0 Answers0