Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering columns in data table by vector of names

Tags:

r

data.table

I am learning data.table and trying to filter certain columns by using a vector containing a set of column names.

> dt <- data.table(A=1:5, B=2:6, C=3:7)
> dt
   A B C
1: 1 2 3
2: 2 3 4
3: 3 4 5
4: 4 5 6
5: 5 6 7
> 
> list <- c("A", "B")
> dt[ ,list, with=FALSE]
   A B
1: 1 2
2: 2 3
3: 3 4
4: 4 5
5: 5 6
> 

This works fine and filter columns. However, the "missing" item in the list will return an error:

> list <- c("A", "B", "D")
> dt[ ,list, with=FALSE]
Error in `[.data.table`(dt, , list, with = FALSE) : 
  column(s) not found: D

How can I ignore the missing column name from the list and return just existing columns from the dt data.table?

like image 821
Suvar Avatar asked Jul 05 '17 13:07

Suvar


People also ask

What is the best approach to filter data from a DataTable based on condition?

Using select method is the best approach to filter data from a data table based on a condition. Explanation: The 'SQL select statement' is used for returning the result of set of records from the given one or more tables of a provided database.

Which object is used to filter rows in the data table?

Introduction to C# DataTable Filter. C# DataTable is a central object used to access most of the objects and data related to the data table. Since the data table comprises data in huge amounts and is not in an organized format, there comes the need to apply a filter.


1 Answers

dt[ ,colnames(dt) %in% list, with=FALSE]
like image 134
R.B Avatar answered Oct 03 '22 12:10

R.B