简体   繁体   English

过滤行值以一组模式结尾的行

[英]Filter rows where column value ends with a set of patterns

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 我需要对该数据集进行子集处理,以便数据集中仅存在File_name以“ .cpp”或“ .h”结尾的行

Use grepl for a base R option: 使用grepl作为基本的R选项:

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

Demo 演示版

A dplyr and stringr solution: dplyrstringr解决方案:

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 : 或仅使用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

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. 我们还可以使用tools包中的file_ext函数来获取文件的文件扩展名,然后将其用于子集数据帧。

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

Base R solution: Base R解决方案:

# 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM