[R] Grep out columns using a list of strings

Boris Steipe boris.steipe at utoronto.ca
Fri May 8 22:37:19 CEST 2015


How about %in% ?


# preparing something that looks like I think your data looks like:
ap <- c("aajkss", "dfghjk", "sdfghk", "xxcvvn")
af <- matrix(1:10, nrow=2)
colnames(af) <- c("aajkss", "b", "c", "dfghjk", "e")

# doing what I think you need done:
ap[ap %in% colnames(af)]


Cheers,
B.

(PS. a reproducible example saves us all time and unnecessary effort. :-)





On May 8, 2015, at 3:50 PM, Kate Ignatius <kate.ignatius at gmail.com> wrote:

> Hi,
> 
> I have a list of 150 strings, say, ap,:
> 
> aajkss
> dfghjk
> sdfghk
> ...
> xxcvvn
> 
> 
> And I would l like to grep out these strings from column names in
> another file, af,.   I've tried the following but none seem to work:
> 
> aps <- af[,grep(ap, colnames(af), value=TRUE)]
> aps <- af[,grep(ap, colnames(af), value=FIXED)]
> aps <- af[,grep(as.character(list(ap),colnames(af))]
> 
> and also aps <- unique (grep(ap, colnames(af))
> 
> Is there another way I can do this - maybe without using grep?
> 
> Thanks!
> 
> Kate.
> 
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> 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.



More information about the R-help mailing list