Safely turn data.table back to data.frame

What is the safest way to get rid / remove the data.table class from an object by returning it back to the data.frame file?

I ask because I use a script that relies on the following code:

 newcol.index <- ncol(my.data) +1 my.data[,newcol.index] <- 3 colnames(my.data)[newcol.index] <- "test" 

The data.table packages do not seem to like it, but fines work using objects of the data.frame class.

+9
source share
3 answers

Based on the discussion in Josh O'Brien's answer, the best way to do this now is setDF since it avoids copying. (This, of course, assumes that you do not need both the data.frame version and the data.table version of your data):

 library(data.table) x <- data.table(a=1:4, b=letters[c(1,1,2,2)], key="a") setDF(x) 
0
source

The as.data.frame method for data.tables is supposedly the safest function to use. (Try getAnywhere("as.data.frame.data.table") to see what it does.)

 library(data.table) DT <- data.table(a=1:4, b=letters[c(1,1,2,2)], key="a") class(as.data.frame(DT)) ## OR: as(X, "data.frame") # [1] "data.frame" 
+14
source

If you want to convert your script to data.table, you can use use := to assign by reference, it will automatically assign the column (ncol(youdata)+1)th , and you can pass the character vector names for the LHS function. It will be assigned by reference, so copying will not be!

 DT <- data.table(a = 1, b = 2) DT[,'test' := 3] DT ab test 1: 1 2 3 
+4
source

All Articles