Skip to content

Reduce does not work with data.table?

2 messages · James Hirschorn, Jeff Newmiller

#
Reduce is failing when applied to a list of elements of class 
data.table. Perhaps this is a bug?

Example:

library(data.table)

dt1 <- data.table(x = 1:3, y = 4:6)
dt2 <- data.table(x = 4:6, y = 1:3)
dt3 <- data.table(x = 0:-2, y = 0:-2)

# This works fine
dt1 + dt2 + dt2
#    x y
# 1: 5 5
# 2: 6 6
# 3: 7 7

# But:
dt_list <- list(dt1, dt2, dt3)
Reduce("+", dt_list)
# Error in f(init, x[[i]]) : non-numeric argument to binary operator
# In addition: Warning message:
# In Reduce("+", dt_list) :
#   Incompatible methods ("Ops.data.frame", "Ops.data.table") for "+"

If I use data.frame instead of data.table, Reduce works properly.
#
This is a design feature of data.table objects, which don't conform to the normal functional programming paradigm that R is usually designed to adhere to and which Reduce expects. Specifically, they normally modify in-place rather than leaving the original object alone. 

In short, don't do that. Read more about how data.tables work. Their benefits come with distinct disadvantages that you need to be very clear about or you will get into trouble like this regularly.