R data.table: Cannot mix positives and negatives -


i want subtract integer (e.g., 20) every row of specific column (e.g., dist column) in data.table below:

require(data.table) cars <- data.table(cars) head(cars)    speed dist 1:     4    2 2:     4   10 3:     7    4 4:     7   22 5:     8   16 6:     9   10 > cars[cars$dist - 20,] error in `[.data.table`(cars, cars$dist - 20, ) :    item 1 of -18 , item 4 2. cannot mix positives , negatives. 

it looks data.table not mixing positive , negative numbers. class of object cars is:

class(cars) # [1] "data.table" "data.frame" 

in terms of benchmarking, want code run fast possible. such, nice see if there perhaps few alternative possible solutions, benchmarked against each other performance speed.

you passing result i variable of [.data.table. can't mix negative (dropping rows) positive values in here.

you similar error data.frame

 x <- data.frame(x=1:5)  x[-1:2] # error in `[.default`(x, -1:2) :  #  0's may mixed negative subscripts  y <- data.table(x=1:5) y[-1:2,] # error in `[.data.table`(y, -1:2, ) :  #  item 1 of -1 , item 3 1. cannot mix positives , negatives. 

your question suggests want pass argument j (and using data.table don't need cars$prefix

cars[ ,dist - 20] 

Comments