1

Given a dataframe with columns names:

"openPrice1", "closePrice1", "openPrice2", "closePrice2", "openPrice3", "closePrice3"...

How can I extract all columns that contain "open"?

For example I want a new dataframe:

"openPrice1", "openPrice2", "openPrice3" ...
John
  • 770
  • 1
  • 9
  • 18
Junxu Chen
  • 61
  • 6

1 Answers1

1

Either we can use startsWith

df1[startsWith(names(df1), "open")]

Or use grep

df1[grep("^open", names(df1))]

Both are base R options


With dplyr

library(dplyr)
df %>%
   select(starts_with('open')
akrun
  • 874,273
  • 37
  • 540
  • 662