jacky_learns_to_code jacky_learns_to_code - 13 days ago 7
R Question

How to remove unwanted features in R?

Suppose I have the following

data
:

'aaa' 'a' 'aaron' 'abcde' 'azz'
x1 ... ... ... ... ...
x2 ... ... ... ... ...
x3 ... ... ... ... ...


Given a pre-defined list of English words , how can I use the
which(.. %in% ..)
operator to get the vector position in order to retain only the features that exist in the pre-defined list of English words?

Expected output:

'a' 'aaron'
x1 ... ...
x2 ... ...
x3 ... ...

Answer

If you have a list of column names you want to keep you can run this:

dat = dat[,which(colnames(dat) %in% list)]

If you have a list of column names you do not want to keep you can run this:

dat = dat[,-which(colnames(dat) %in% list)]

If you're using a data.table you're going to have to include with=FALSE for this to work.

dat = dat[,which(colnames(dat) %in% list),with = FALSE]
Comments