R语言 如何根据字符串匹配来删除R数据框架的行
在这篇文章中,我们将讨论如何在R编程语言中基于字符串匹配来删除数据框架的行。
为此,可以使用grep()函数。这个函数在一个字符串向量中搜索某些字符模式的匹配,如果该字符串存在,则返回一个布尔值,即TRUE,否则返回FALSE。
语法: grepl(pattern, string, ignore.case=FALSE)
参数 。
- pattern:正则表达式模式
- string:要搜索的字符向量
首先,在grepl()的帮助下,我们获得了包含指定子字符串的行。然后使用Not运算符(!),我们在数据框中删除了这些行,并将它们存储在另一个数据框中。
使用中的数据框 。
数据框
例1 :
Strings<-c("Geeks","For","Geeks","GFG","Ram",
"Ramesh","Gene","Siri")
Id<-1:8
# df is our data frame name
df<-data.frame(Id,Strings)
print(df)
# Removes the rows in Data frame
# which consist "Ra" in it
new_df=df[!grepl("Ra",df$Strings),]
print(new_df)
输出 。
例2 :
Strings<-c("Geeks","For","Geeks","GFG","Ram",
"Ramesh","Gene","Siri")
Id<-1:8
# df is our data frame name
df<-data.frame(Id,Strings)
print(df)
# Removes the rows in Data frame
# which consist "Ge" in it
new_df=df[!grepl("Ge",df$Strings),]
print(new_df)
输出 。