To apply ifelse
to alter a column in data.table
while grouping it, you can use the :=
operator to create a new column or replace an existing column based on a condition. Here's an example:
library(data.table)
# create sample data.table
dt <- data.table(x = c("A", "B", "C", "D"), y = c(1, 2, 3, 4))
# apply ifelse to alter 'y' column based on condition of 'x' column
dt[, y_new := ifelse(x == "A", y * 2, y)]
# output updated data.table
dt
In this example, we're altering the y
column based on the condition that x == "A"
. If the condition is met, we're multiplying y
by 2 and otherwise keeping it the same. The resulting updated data.table
includes a new column y_new
with the altered values.
Asked: 2023-06-07 22:51:40 +0000
Seen: 11 times
Last updated: Jun 07 '23