Grep out columns using a list of strings

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

Grep out columns using a list of strings

Beejai
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.

______________________________________________
[hidden email] 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.
Reply | Threaded
Open this post in threaded view
|

Re: Grep out columns using a list of strings

Boris Steipe
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 <[hidden email]> 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.
>
> ______________________________________________
> [hidden email] 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.

______________________________________________
[hidden email] 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.