Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we setDT on multiple object all at once?

Tags:

r

data.table

I need to load many rds files from outside, to make things go much smoother, I tend to setDT on the objects.

Is it possible to setDT all at once? I tried:

lapply(ls(), setDT)
lapply(list(ls()), setDT)
for(i in ls()) setDT(i)

#Error in FUN(X[[i]], ...) : 
#  Argument 'x' to 'setDT' should be a 'list', 'data.frame' or 'data.table'

The results are all the same. Is there more graceful way to doing this?

p.s. A friend advised using do.call:

do.call(setDT, list("A", "B", "C"))

but that seems not to be working.

like image 207
Grec001 Avatar asked Nov 22 '25 12:11

Grec001


1 Answers

You can Filter data.frames in an environment and apply setDT to those:

all_data_tables = Filter(function(x) is.data.frame(eval(as.name(x))), ls())
lapply(all_data_tables, function(x) setDT(eval(as.name(x))))

You can also potentially replace is.data.frame with is.list or something more complicated, but I think is.data.frame covers your use case.

You can also use get and could also be more careful about specifying envir in ls/eval/get.

like image 129
MichaelChirico Avatar answered Nov 25 '25 05:11

MichaelChirico