Reputation: 623
I have a data set as follows
File_name Folder
ord.cpp 1
rod.ibo 1
ppol.h 2
lko.cpp 3
rto.cp 3
tax.mo 2
t_po..lo.cpp 4
I need to subset this data set so that only rows where File_name ends with ".cpp" or ".h" is present in the data set
Upvotes: 1
Views: 6631
Reputation: 39858
A dplyr
and stringr
solution:
df %>%
filter(str_detect(File_name, ".cpp|.h"))
File_name Folder
1 ord.cpp 1
2 ppol.h 2
3 lko.cpp 3
4 t_po..lo.cpp 4
Or with just dplyr
:
df %>%
filter(grepl(".cpp|.h", File_name))
File_name Folder
1 ord.cpp 1
2 ppol.h 2
3 lko.cpp 3
4 t_po..lo.cpp 4
Upvotes: 2
Reputation: 3221
Base R solution:
# Looking for a string eding with .cpp or .h
df[endsWith(df$File_name,(".cpp"))|endsWith(df$File_name,(".h")),]
Output:
File_name Folder
1 ord.cpp 1
3 ppol.h 2
4 lko.cpp 3
7 t_po..lo.cpp 4
Upvotes: 1
Reputation: 388862
We can also use file_ext
function from tools
package to get file extensions of the file and then use it to subset data frame.
library(tools)
df[file_ext(df$File_name) %in% c("cpp", "h"), ]
# File_name Folder
#1 ord.cpp 1
#3 ppol.h 2
#4 lko.cpp 3
#7 t_po..lo.cpp 4
Upvotes: 0
Reputation: 520968
Use grepl
for a base R option:
df_subset <- df[grepl("\\.(?:cpp|h)$", df$File_name), ]
df_subset
File_name Folder
1 ord.cpp 1
3 ppol.h 2
4 lko.cpp 3
7 t_po..lo.cpp 4
Upvotes: 2