>我有一个数据集如下
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
我需要对这个数据集进行子集化,以便数据集中只存在File_name以".cpp"或".h"结尾的行
将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
演示
dplyr
和stringr
解决方案:
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
或者只需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
基本 R 解决方案:
# Looking for a string eding with .cpp or .h
df[endsWith(df$File_name,(".cpp"))|endsWith(df$File_name,(".h")),]
输出:
File_name Folder
1 ord.cpp 1
3 ppol.h 2
4 lko.cpp 3
7 t_po..lo.cpp 4
我们还可以使用包file_ext
函数来获取文件的文件扩展名tools
然后将其用于子集数据框。
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