Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does data.table not know "J"?

I run RStudio in debug mode to check some feature in a package (which uses data.table and is working since 2 years). Now I face the following situation in some function:

routes[J(x1, y1, x2, y2), nomatch = 0L]

Error in J(x1, y1, x2, y2) : could not find function "J"

As said: This package works and library(data.table) is set.

Now I thought, I do a small check as suggested here - the environment is unchanged:

dt = data.table( id = 1L, start = c( 9, 21, 5 ), end = c( 10, 22, 7 ) )
data.table::setkey(dt, "start")
dt[J(1), nomatch = 0L]

Empty data.table (0 rows) of 3 cols: id,start,end

and I get the correct result? I anybody has an idea, how to create a reproducable example, I will try. This does not make any sense to me... So I tried again, but

routes[J(x1, y1, x2, y2), nomatch = 0L]

Error in J(x1, y1, x2, y2) : could not find function "J"

Any hint highly appreciated

Screenshot:

enter image description here

Reproducible example with more than one parameter in data.table:

library(data.table)
r <- data.table::data.table(lat1 = numeric(0), lng1 = numeric(0),
                            lat2 = numeric(0), lng2 = numeric(0), 
                            time = numeric(0))
data.table::setkey(r, lat1, lng1, lat2, lng2)

lat1 = 1
lat2 = 2
lng1 = 11
lng2 = 22
li <- data.table::data.table(lat1=lat1, lng1=lng1, lat2=lat2, lng2=lng2, time=time)
r <- rbindlist(list(r, li))
data.table::setkey(r, lat1, lng1, lat2, lng2)

r[J(1, 11, 2, 22), nomatch = 0L]
# lat1 lng1 lat2 lng2       time
# 1:    1   11    2   22 <function>
r[J(1, 11, 2, 0), nomatch = 0L]
# Empty data.table (0 rows) of 5 cols: lat1,lng1,lat2,lng2,time

But still:
routes[J(1, 11, 2, 22), nomatch = 0L]
# Error in J(1, 11, 2, 22) : could not find function "J"
like image 350
Christoph Avatar asked Dec 31 '22 14:12

Christoph


1 Answers

J is not a function. It is an alias that is replaced before evaluation:

https://github.com/Rdatatable/data.table/blob/master/R/data.table.R#L102

I suspect routes is not a data.table.

Adding my comments here, because they illustrate my thought process which let to the solution:

I've answered a very similar question where someone was looking for the . function. So, I was pretty sure about that and only needed to search the source code for J. Once I had confirmed that is was an alias like ., it was easy to deduce that [.data.table couldn't have been called by your code.

You called [ which has (more than) 2 parameters. So, no error there. Only when the first parameter is evaluated, you can get an error.

like image 107
Roland Avatar answered Jan 11 '23 04:01

Roland