Consider the following data:
data <- data.table(ID = 1:10, x = c(1,1,0,0,0,1,1,0,0,1), y = c(0,0,1,1,1,1,1,0,1,1))
I want to assign the following value in a column new: For each pair of x and y (e.g. x = 1 and y = 1), find the row highest up in the list where this specific pair occurs and let new be the ID of this row. For example, for all rows where x = 1 and y = 1, I want to new to be 6.
The following line of code seems to do precisely that:
data[, new := head(.SD, 1), .(x, y)]
My question is just, why does this work? head(.SD, 1) will be a list containing one row, how can R know I want to assign specifically the value in the first column of head(.SD, 1) to new? I was expecting an error when trying to run this code, but I do actually get the desired output.