Alex Bădoi Alex Bădoi - 10 days ago 7
R Question

How to grep partial string? R

I have a file called

data
with roughly 2000 columns named as follows:

Open-YV2004
High-YV2004
Low-YV2004
Settle-YV2004
Change-YV2004
Wave-YV2004
Volume-YV2004
Prev. Day Open Interest-YV2004
EFP Volume-YV2004
EFS Volume-YV2004
Block Volume-YV2004


the others continue to have the same names but a different prefix (
YV2004
above)

Currently I am using:

Volume <- new[,grep("Volume", colnames(data))]


this greps all columns containing
"Volume"
in their name:

Volume-YV2004
EFP Volume-YV2004
EFS Volume-YV2004
Block Volume-YV2004


I would like to take just the ones containing
"Volume"
only

Solution:

Volume-YV2004

Answer

You can use ^ in your regular expression to indicate that the wanted string must start with the text that follows:

Volume <- new[,grep("^Volume", colnames(data))]