Here's one that is perhaps a little simpler: simply drop the which and use logical indexing.
dat <- matrix(1:6, 2); colnames(dat) <- c("A","B","A") dat[, colnames(dat) %in% "A"] dat[, colnames(dat) %in% "B"] # Note that you may want drop = FALSE dat[, colnames(dat) %in% "C"] dat[, !(colnames(dat) %in% "A")] # Note that you may want drop = FALSE dat[, !(colnames(dat) %in% "B")] dat[, !(colnames(dat) %in% "C")] Michael On Thu, Dec 8, 2011 at 7:42 AM, andrija djurovic <djandr...@gmail.com> wrote: > Hi. Here is one approach: > > if (length(b)>0) data[,-b] else data > > Andrija > > On Thu, Dec 8, 2011 at 1:25 PM, Vikram Bahure > <economics.vik...@gmail.com>wrote: > >> Dear R users, >> >> I have a very simple query. >> >> I am using the following command, which should give me row no. for the >> matching colnames. It works well for matching the colnames but if there is >> no column matching it gives me outcome as integer(0) which I am not able to >> use in further calculation. It would be very helpful to have some insight. >> * >> * >> *> b <- which(colnames(data)%in%c("X.","X"))* >> *> b* >> *integer(0)* >> *> b>0* >> *logical(0)* >> *>b<- data[,-b] # does not work properly* >> * >> * >> Regards >> Vikram >> >> [[alternative HTML version deleted]] >> >> ______________________________________________ >> R-help@r-project.org mailing list >> https://stat.ethz.ch/mailman/listinfo/r-help >> PLEASE do read the posting guide >> http://www.R-project.org/posting-guide.html >> and provide commented, minimal, self-contained, reproducible code. >> > > [[alternative HTML version deleted]] > > ______________________________________________ > R-help@r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide http://www.R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code. ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.