if
is not vectorized, Replace it with y <- ifelse(x == 0, 1, 0)
.
You don't really need a custom function in my opinion:
dt[,op_event := ifelse(event == 0, 1, 0)]
Question
I have following data table
user_id user_system_days event total_pics
[1,] 21196680 0 0 124
[2,] 21197699 0 0 4
[3,] 21197861 0 0 14
[4,] 21198820 1 0 21
[5,] 21199601 0 0 3
[6,] 21203847 0 0 1
Based on a value in column event I want to insert a column to the data table, My approach was by writing a function, and use that function to return a value.
opposite_event <- function(x) {
y <- 1
if (x == 1)
y <- 0
return (y)
}
I called function as follows:
dt[,op_event:=opposite_event(dt$event)]
This actually added the column but values were wrong:
user_id user_system_days event total_pics op_event
[1,] 21196680 0 0 124 0
[2,] 21197699 0 0 4 0
[3,] 21197861 0 0 14 0
[4,] 21198820 1 0 21 0
[5,] 21199601 0 0 3 0
[6,] 21203847 0 0 1 0
Based on my function if value of the dt$event
is 1
then return value should be 0
and if dt$event
is 0 then return value should 1
Plus I wasn't sure how to insert the column into a specific location like right after event column.
Solution
if
is not vectorized, Replace it with y <- ifelse(x == 0, 1, 0)
.
You don't really need a custom function in my opinion:
dt[,op_event := ifelse(event == 0, 1, 0)]