如何根据字符串匹配删除R数据帧的行?
在本文中,我们将讨论如何在 R 编程语言中基于字符串匹配删除数据帧的行。
为此可以使用 grep()函数。如果该字符串存在,否则返回FALSE这对的矢量某个字符模式匹配函数的搜索,并返回一个布尔值TRUE。
Syntax: grepl(pattern, string, ignore.case=FALSE)
Parameter:
- pattern: regular expressions pattern
- string: character vector to be searched
首先在 grepl() 的帮助下,我们获得了其中包含指定子字符串的行。然后使用 Not运算符(!),我们删除了数据框中的那些行,并将它们存储在另一个数据框中。
使用中的数据框:
示例 1:
R
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)
R
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)
输出:
示例 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)
输出: