R 筛选列值以一组模式结尾的行
我有一个如下的数据集R 筛选列值以一组模式结尾的行,r,regex,dplyr,R,Regex,Dplyr,我有一个如下的数据集 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 我需要将此数据集子集,以便在数据集中仅存在文件名以“.cpp”或“.h”结尾的行使用grepl作为基本R选项: df_subset <- df[grepl("\\.(?:cpp|h)$",
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
我需要将此数据集子集,以便在数据集中仅存在文件名以“.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
df_子集使用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
df_subset我们还可以使用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
我们还可以使用tools
包中的file\u 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
基本R解决方案:
# Looking for a string eding with .cpp or .h
df[endsWith(df$File_name,(".cpp"))|endsWith(df$File_name,(".h")),]
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
输出:
File_name Folder
1 ord.cpp 1
3 ppol.h 2
4 lko.cpp 3
7 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")),]
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
输出:
File_name Folder
1 ord.cpp 1
3 ppol.h 2
4 lko.cpp 3
7 t_po..lo.cpp 4
一个dplyr
和stringr
解决方案:
# Looking for a string eding with .cpp or .h
df[endsWith(df$File_name,(".cpp"))|endsWith(df$File_name,(".h")),]
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
一个dplyr
和stringr
解决方案:
# Looking for a string eding with .cpp or .h
df[endsWith(df$File_name,(".cpp"))|endsWith(df$File_name,(".h")),]
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
subset(df,grepl(\\.(?:cpp|h)$”,File|u name))
just n casesubset(df,grepl(\.(?:cpp|h)$”,File|u name))
just n case这是不正确的,因为它还将选择诸如ord.mcpp
甚至ppol.mhjh
等不正确的值correct@Onyambu:我已经更新了我的答案。你能给我你的反馈吗?这是不正确的,因为它还会选择像ord.mcpp
或甚至ppol.mhjh
等不正确的值correct@Onyambu:我已经更新了我的答案。你能给我你的反馈吗?