Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: Removing multiple columns from data frame based on vector values

Tags:

r

vector

I have a data frame dataGL_all:

Date<-c("01-01-15 04:00","01-01-15 04:20","01-01-15 04:40")
FLIin<-c(96,39,72)
FLIout<-c(173,147,103)
FBEin<-c(96,116,166)
FBEout<-c(32,53,120)
dataGL_all<-data.frame(Date, FLIin, FLIout, FBEin, FBEout)

Furthermore, I have a vector:

Remove <- c("FBEin", "FLIout")

I would a piece of code that removes the columns in the vector Remove from the data frame dataGL_all. I have tried many combinations of functions (e.g. grep(), c() and names()) but can't get it working ... would appreciate help :) thx

P.S. My "real" data frame contains 68 columns where of I would like to remove 36 (the ones in the vector).

like image 574
LarsGustafsson Avatar asked Jul 29 '26 20:07

LarsGustafsson


1 Answers

dataGL_all[, !names(dataGL_all) %in% Remove]

should do the trick. Or, if you want grep:

dataGL_all[, grep(paste(Remove, collapse = "|"), names(dataGL_all), invert = T)]
like image 129
lukeA Avatar answered Aug 01 '26 13:08

lukeA



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!