Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: how to delete columns in a data.table?

Tags:

r

data.table

Question about the R package data.table: how are multiple data.table columns removed in a memory-efficient way?

Suppose the column names to be deleted are stored in the vector deleteCol.

In a data.frame, it is:
DF <- DF[deleteCol] <- list()

For data.table, I tried:

DT[, deleteCol, with=FALSE] <- list()

but this gave unused argument(s) (with = FALSE)

like image 622
Martijn Tennekes Avatar asked May 14 '12 09:05

Martijn Tennekes


People also ask

How do I delete a column in a table?

Right-click in a table cell, row, or column you want to delete. On the Mini toolbar, click Delete. Choose Delete Cells, Delete Columns, or Delete Rows.

How do I remove multiple columns in R?

We can delete multiple columns in the R dataframe by assigning null values through the list() function.

How do I remove column names in R?

Drop Columns by Name Using %in% Operator We are using the %in% operator to drop or delete the columns by name from the R data frame, This operator will select the columns by name present in the list or vector.


1 Answers

ok here are a few options. The last one seems exactly what you want...

 x<-1:5
 y<-1:5
 z<-1:5
 xy<-data.table(x,y,z)
 NEWxy<-subset(xy, select = -c(x,y) ) #removes column x and y

and

id<-c("x","y")
newxy<-xy[, id, with=FALSE]
newxy #gives just x and y e.g.

   #  x y
#[1,] 1 1
#[2,] 2 2
#[3,] 3 3
#[4,] 4 4
#[5,] 5 5

and finally what you really want:

anotherxy<-xy[,id:=NULL,with=FALSE] # removes comuns x and y that are in id

#     z
#[1,] 1
#[2,] 2
#[3,] 3
#[4,] 4
#[5,] 5
like image 157
user1317221_G Avatar answered Oct 12 '22 07:10

user1317221_G