Reputation: 145
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"
Upvotes: 1
Views: 449
Reputation: 887691
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]
Upvotes: 1