Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select columns by class (e.g. numeric) from a data.table

Tags:

r

data.table

Why doesn't this work with data.table?

It works with data.frame. Is there a way to do this with a data table?

x <- data.table(v1=1:20,v2=1:20,v3=1:20,v4=letters[1:20])
y <- x[ , sapply(x, is.numeric)]

This returns:

v1    v2    v3    v4
TRUE  TRUE  TRUE FALSE
like image 533
Fred R. Avatar asked Aug 05 '14 03:08

Fred R.


People also ask

How do I select only numeric columns from a data frame?

To select columns that are only of numeric datatype from a Pandas DataFrame, call DataFrame. select_dtypes() method and pass np. number or 'number' as argument for include parameter.

How do I select a column by number in R?

To select a column in R you can use brackets e.g., YourDataFrame['Column'] will take the column named “Column”. Furthermore, we can also use dplyr and the select() function to get columns by name or index. For instance, select(YourDataFrame, c('A', 'B') will take the columns named “A” and “B” from the dataframe.

How do I select a group of columns in R?

To pick out single or multiple columns use the select() function. The select() function expects a dataframe as it's first input ('argument', in R language), followed by the names of the columns you want to extract with a comma between each name.


2 Answers

From data.table 1.13.0 ".SDcols accepts a function which is used to select the columns of .SD". Thus, simply .SDcols = is.numeric:

x[ , .SD, .SDcols = is.numeric]
like image 103
Artem Klevtsov Avatar answered Oct 16 '22 19:10

Artem Klevtsov


data.table needs the with=FALSE to grab column numbers.

tokeep <- which(sapply(x,is.numeric))
x[ , tokeep, with=FALSE]
like image 14
Mike.Gahan Avatar answered Oct 16 '22 19:10

Mike.Gahan