Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

split data.table

Tags:

r

data.table

I have a data.table which I want to split into two. I do this as follows:

dt <- data.table(a=c(1,2,3,3),b=c(1,1,2,2))
sdt <- split(dt,dt$b==2)

but if I want to to something like this as a next step

sdt[[1]][,c:=.N,by=a]

I get the following warning message.

Warning message: In [.data.table(sdt[[1]], , :=(c, .N), by = a) : Invalid .internal.selfref detected and fixed by taking a copy of the whole table, so that := can add this new column by reference. At an earlier point, this data.table has been copied by R. Avoid key<-, names<- and attr<- which in R currently (and oddly) may copy the whole data.table. Use set* syntax instead to avoid copying: setkey(), setnames() and setattr(). Also, list(DT1,DT2) will copy the entire DT1 and DT2 (R's list() copies named objects), use reflist() instead if needed (to be implemented). If this message doesn't help, please report to datatable-help so the root cause can be fixed.

Just wondering if there is a better way of splitting the table so that it would be more efficient (and would not get this message)?

like image 487
jamborta Avatar asked Feb 20 '13 10:02

jamborta


People also ask

How do you split data in a table?

Split tables if you want your data separated into two tables. In the row that you want to be first in the new table, select a cell. Select Table Tools Layout > Split Table. Note: If the new table contains multiple rows, it can also be split.

Why would we want to split data into separate tables?

In many cases, it may be best to split information into multiple related tables, so that there is less redundant data and fewer places to update.

How do I split a list into two columns in R?

To split a column into multiple columns in the R Language, we use the separator() function of the dplyr package library. The separate() function separates a character column into multiple columns with a regular expression or numeric locations.


1 Answers

As mentionned above (@jangorecki), the package data.table already has its own function for splitting. In that simplified case we can use:

> dt <- data.table(a = c(1, 2, 3, 3), b = c(1, 1, 2, 2))
> split(dt, by = "b")
$`1`
   a b
1: 1 1
2: 2 1

$`2`
   a b
1: 3 2
2: 3 2

For more difficult/concrete cases, I would recommend to create a new variable in the data.table using the by reference functions := or set and then call the function split. If you care about performance, make sure to always remain in the data.table environment e.g., dt[, SplitCriteria := (...)] rather than computing the splitting variable externallly.

like image 150
Jeffery Petit Avatar answered Oct 20 '22 09:10

Jeffery Petit