warship
warship

Reputation: 3024

R data.table: Cannot mix positives and negatives

I want to subtract an integer (e.g., 20) from every row of a specific column (e.g., dist column) in the 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 i is -18 and item 4 is 2. Cannot mix positives and negatives.

It looks like data.table does not like mixing positive and negative numbers. The class of my object CARS is:

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

In terms of benchmarking, I want my code to run as fast as possible. As such, it would be nice to see if there are perhaps a few alternative possible solutions, benchmarked against each other for performance speed.

Upvotes: 1

Views: 1269

Answers (2)

mnel
mnel

Reputation: 115392

You are passing the result to the i variable of [.data.table. You can't mix negative (dropping rows) with positive values in here.

You get a similar error with a data.frame

 x <- data.frame(x=1:5)
 x[-1:2]
# Error in `[.default`(x, -1:2) : 
#  only 0's may be mixed with negative subscripts

y <- data.table(x=1:5)
y[-1:2,]
# Error in `[.data.table`(y, -1:2, ) : 
#  Item 1 of i is -1 and item 3 is 1. Cannot mix positives and negatives.

Your question suggests you want to pass the argument to j (and using data.table you don't need CARS$prefix

CARS[ ,dist - 20]

Upvotes: 5

Lance
Lance

Reputation: 39

If your goal is to replace all negative numbers with 0, a simple solution would be:

CARS[(dist - 20)<=0,dist:=0]

CARS[(dist - 20)>0,dist:dist-20]

Upvotes: -1

Related Questions