1

I have a data.table with columns A, B and C

A | B | C

1 | 1 | 2

2 | 1 | 2

2 | 3 | 1

I want to change the values of each column to "True" (if the row value == 2) or "False" otherwise, programmatically.

I know that dt[, A := fifelse(A == 2, "True", "False"] works, but how do I pass in the columns as a variable? Something like dt[, cols := fifelse(cols := 2, "True", "False"], where cols = "A"

  • Related Q: https://stackoverflow.com/questions/24833247/how-can-one-work-fully-generically-in-data-table-in-r-with-column-names-in-varia – jangorecki Dec 01 '20 at 07:52

1 Answers1

1

It is better to leave it as boolean TRUE/FALSE instead of a string "True", "False"

dt[, A := A == 2]

If we need to pass a variable and it is only for a single column, get can be used

dt[, (cols) := get(cols) == 2]

If there are more than one column, specify it in .SDcols, loop over the .SD, convert to logical and assign (:=) it back to the strings of object

dt[, (cols) := lapply(.SD, `==`, 2), .SDcols = cols]
akrun
  • 874,273
  • 37
  • 540
  • 662